(function() {
	'use strict';

	angular.module('uniflash').directive('ufProperty', property);

	function property() {
		var directive = {
			restrict: 'E',
			templateUrl: 'flash_properties/property.html',
			controller: PropertyController,
			controllerAs: 'vm',
			link: function(scope, element, attrs) {
				scope.vm.setProp(attrs.id);
				scope.vm.minimal = attrs.minimal;
				scope.vm.searchable = attrs.searchable==='true';
			},
			scope:{}
		};

		return directive;
	}

	PropertyController.$inject = ['$sce','ufPropertiesDB','ufPropertiesValue','propertiesActionSrv','ufSettingsDisplayControlSrv','ticHighlightSrv','ufContext','ufPropertyRules'];
	
	function PropertyController($sce,ufPropertiesDB,ufPropertiesValue,propertiesActionSrv,ufSettingsDisplayControlSrv,ticHighlightSrv,ufContext,ufPropertyRules) {
		var vm = this;
		vm.ufPropertiesDB = ufPropertiesDB;
		vm.ufPropertiesValue = ufPropertiesValue;
		vm.propertiesActionSrv = propertiesActionSrv;
		vm.ufSettingsDisplayControlSrv = ufSettingsDisplayControlSrv;
		vm.ticHighlightSrv = ticHighlightSrv;
        vm.ufContext = ufContext;
		vm.setProp = function(id) {
			vm.id = id;
			vm.curProperty = ufPropertiesDB.getProperty(id,ufContext.getCurrentCore().name);
            vm.valueObj = ufPropertiesValue.getValueObj(vm.curProperty._id,vm.ufContext.getCurrentCore().name);
		};
		
		vm.getFilter = function() {
			if ( vm.searchable ) {
				return ufPropertiesDB.getFilter();
			} else {
				return '';
			}
		};
		
		vm.getInputWidth = function(input) {
			if ( input ) {
				let width = input.toString().length * 8;
				
				if ( width < 150 ) {
					return '150px';
				} else {
					return width.toString()+'px';
				}
			}
			return '150px';
		};
		
		vm.valueChanged = function() {
			vm.valueObj.modified = true;
			ufPropertyRules.resolvePropertyRules(vm.id,ufContext.getCurrentCore().name,vm.valueObj);
		};
		
		vm.checkValue = function() {
			// error checking for lower bound value
			if ( vm.curProperty.valueType === 'Numeric' ) {
				let lowerInt = parseInt(vm.curProperty.lower) || 0;
				
				if ( vm.valueObj.value < lowerInt ) { 
					vm.valueObj.value = lowerInt;
				}
			}
			// error checking for upper bound value
			if ( vm.curProperty.valueType === 'Numeric' && vm.curProperty.upper ) {
				let upperInt = parseInt(vm.curProperty.upper);
				
				if ( vm.valueObj.value > upperInt ) { 
					vm.valueObj.value = upperInt;
				}
			}
		};
	}

})();
