(function() {
	'use strict';

	angular.module('uniflash').directive('ufUtilities', Utilities);

	function Utilities() {
		var directive = {
			restrict: 'E',
			templateUrl: 'flash_properties/utilities.html',
			controller: UtilitiesController,
			controllerAs: 'vm',
			scope:{}
		};

		return directive;
	}

	UtilitiesController.$inject = ['$state', 'ufPropertiesDB', 'ufPropertiesValue', 'propertiesActionSrv', 'ufSession', 'ufSearch'];
	
	function UtilitiesController($state, ufPropertiesDB, ufPropertiesValue, propertiesActionSrv, ufSession, ufSearch) {
		var vm = this;
		
		vm.ufPropertiesDB = ufPropertiesDB;
		vm.ufPropertiesValue = ufPropertiesValue;
		vm.propertiesActionSrv = propertiesActionSrv;
		vm.ufSession = ufSession;
		
		vm.propertyListFilter = 1;
		vm.showButtonOnly = false;
		vm.propCoreSelect = 'All';
		vm.categoryFilter = 'All';
		vm.settingsUtilFilter = ufPropertiesDB.getFilter();
		vm.displaySelect = '0';
		
		// Custom filter for MSP430
		if ( $state.params.deviceXMLFile.indexOf('MSP430') !== -1 ) {
			vm.propCoreSelect = 'MSP430';
		}
		
		vm.setCategoryFilter = function(cat) {
			vm.categoryFilter = cat;
		};
		
		// filter for the property list
		vm.propListFilter = function(prop) {
			// show only buttons
			if ( vm.showButtonOnly && prop.valueType !== 'Button' ) { return false; }
			
			// show only the selected core properties (match target string or if property is generic)
			if ( (vm.propCoreSelect !== 'All') && !ufPropertiesDB.matchTarget(prop,vm.propCoreSelect) ) { return false; }
			
			// filtering ID and name based on the given string
			if ( (prop._id.toLowerCase().indexOf(ufSearch.searchStr.toLowerCase()) === -1) && 
				 (prop.name.toLowerCase().indexOf(ufSearch.searchStr.toLowerCase()) === -1) ) { return false; }

			// custom case to remore clock control properties from MSP430
			if ( (vm.propCoreSelect === 'MSP430') && ( (prop._id.indexOf('ClockControl') !== -1) || (prop._id.indexOf('ClockDesc') !== -1) ) ) { return false; }
				 
			// category does not match
			if ( (vm.categoryFilter !== 'All') && !ufPropertiesDB.matchCategory(prop,vm.categoryFilter) ) { return false; }
				 
			return true;
		};
		
		// filter for the value list (filters on propertyListFilter (0 => show All, 1 => show only modified))
		vm.valueListFilter = function(curValue) {
			if ( vm.propertyListFilter === 0 ) { return true; }
			return ( ( vm.propertyListFilter === 1 ) && curValue.modified );
		};
	}

})();
