angular.module("app").directive("projectConditions", function($rootScope, $q, ProjectConditionsService, UniqueIdGenerator, L, DatabankService, SQEvents) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "../app/directives/projectConditions/projectConditions.html",
        scope: {
            conditions: '=',
            instance : '='
        },
        link: function ($scope, element, attrs) {

            function loadDatabanks() {
                DatabankService.loadVisibleDatabanks($scope.databanks);
            }

            $scope.onAddCondition = function(){
                editMode = false;
        
                $scope.curCondition.type = $scope.conditionTypes[0].type;
                $scope.curCondition.title = $scope.conditionTypes[0].title;
                $scope.curCondition.descriptionFormat = $scope.conditionTypes[0].descriptionFormat;
                $scope.curCondition.fields = $scope.conditionTypes[0].fields;
                
                tryInitDurationFields($scope.curCondition.fields);
        
                showPopup("#" + $scope.id);
            }
        
            $scope.onConditionClick = function(condition, index){
                editMode = true;
                conditionIndex = index;
                
                $scope.curCondition.type = condition.type;
                $scope.curCondition.title = condition.title;
                $scope.curCondition.descriptionFormat = condition.descriptionFormat;
                $scope.curCondition.fields = condition.fields;
                
                tryInitDurationFields($scope.curCondition.fields);

                showPopup("#" + $scope.id);
            }

            $scope.onSelectConditionType = function(){
                var conditionType = getItem($scope.conditionTypes, 'type', $scope.curCondition.type);
        
                $scope.curCondition.type = conditionType.type;
                $scope.curCondition.title = conditionType.title;
                $scope.curCondition.descriptionFormat = conditionType.descriptionFormat;
                $scope.curCondition.fields = angular.copy(conditionType.fields);

                tryInitDurationFields($scope.curCondition.fields);
            }
        
            $scope.getConditionDescription = function(condition){
                if(!condition.descriptionFormat) return condition.title;
        
                var params = [];
                for(var i=0; i<condition.fields.length; i++){
                    var field = condition.fields[i];
                    if(field.type == $scope.projectConditionFields.duration){
                        var runtime = "";
                        if(field.days > 0){
                            runtime += field.days + "d ";
                        }
                        if(field.hours > 0){
                            runtime += field.hours + "h ";
                        }

                        runtime += field.minutes + "m";

                        params.push(runtime);
                    }
                    else params.push(field.value);
                }
        
                return condition.descriptionFormat.format(params);
            }
        
            $scope.getConditionTitle = function(){
                var conditionType = getItem($scope.conditionTypes, 'type', $scope.curCondition.type);
                return conditionType ? conditionType.title : '';
            }
        
            $scope.getComparatorLabel = function(value){
                var comparator = getItem($scope.comparators, 'value', value);
                return comparator ? comparator.name : '';
            }
        
            $scope.onRemoveCondition = function(index){
                $rootScope.showConfirm(
                    L.tsq("Removing condition"), 
                    L.tsq("Are you sure you want to remove selected condition?"),
                    function(confirmed){
                        if(confirmed){
                            $scope.conditions.splice(index, 1);

                            try { $scope.$digest(); } catch(err){}

                            if($scope.instance.onChange) $scope.instance.onChange();
                        }
                    },
                    true
                );
            }
        
            $scope.onSaveCondition = function(){
                if(editMode){
                    $scope.conditions[conditionIndex] = angular.copy($scope.curCondition);
                }
                else {
                    $scope.conditions.push(angular.copy($scope.curCondition));
                }
                
                hidePopup("#" + $scope.id);
                
                if($scope.instance.onChange) $scope.instance.onChange();
            }

            function tryInitDurationFields(fields){
                for(var i=0; i<fields.length; i++){
                    var field = fields[i];
                    if(field.type == $scope.projectConditionFields.duration){
                        ProjectConditionsService.setDurationInDHM(field);
                    }
                }
            }
            
            function onEvent(event, data){
                if(event == SQEvents.get("RELOAD_DATABANKS")){
                    loadDatabanks();
                } 
                else return;
        
                try { $scope.$digest(); } catch(er) {}
            }

            $scope.$on("$destroy", function(){
                UniqueIdGenerator.removeId($scope.id);
                SQEvents.removeListener(listenerId);
            });
            
            var editMode = false;
            var conditionIndex = -1;

            $scope.id = UniqueIdGenerator.generateId();

            $scope.projectConditionFields = ProjectConditionsService.projectConditionFields;
            $scope.conditionTypes = ProjectConditionsService.conditionTypes;
            $scope.comparators = ProjectConditionsService.comparators;

            $scope.curCondition = {};

            $scope.comparators = [
                { name: L.tsq('is bigger'), value: '>' },
                { name: L.tsq('is bigger or equal'), value: '>=' },
                { name: L.tsq('is equal'), value: '=' },
                { name: L.tsq('is lower'), value: '<' },
                { name: L.tsq('is lower or equal'), value: '<=' }
            ];

            $scope.databanks = [];

            loadDatabanks();

            var listenerId = "ProjectConditions-" + $scope.id;
            SQEvents.addListener(listenerId, [SQEvents.get("RELOAD_DATABANKS")], onEvent);
        }
    };
});