'use strict';

angular.module('cs.filter', []).controller('csFilterCtrl', 
	function($scope, csFilters, $timeout){
		// load csFilters values into models
		$scope.dateFormat = "dd.MM.yyyy";
		$scope.dateFilter = csFilters.dateFilter; // date/time
		$scope.statusFilter = csFilters.statusFilter; // selected status filter type
		$scope.dateObj = {};
		$scope.dateObj.dateFilterType = csFilters.dateFilterType; // date filter, filter by:
		$scope.selectFilterModel = csFilters.selectFilter; // filter selected (service, state, task, or no filter)
		$scope.typeFilter = csFilters.typeFilter; // list of selected service/state/task types
		$scope.typeFilterList = []; // selected list (service, state, or task types)
		
		$scope.serviceTypes = csFilters.existingServiceTypes; // list of all service types
		$scope.stateTypes = csFilters.existingStateTypes; // list of all state types
		$scope.taskTypes = csFilters.existingTaskTypes; // list of all task types
		$scope.quickFilterCategories = ['Show All', 'This Month', 'Last Month', 'Last 90 Days', 'This Year', 'Last Year', 'Custom Range'];
		$scope.statusCategories = ['Select All','Active','Completed'];
		$scope.filterByDateCategories = ['Starting', 'Ending', 'Starting and Ending', 'Starting or Ending'];
		$scope.existingFilters = ["No Filter"];
		if (csFilters.queryType == "Service ID"){
			$scope.existingFilters.push("State", "Task");
		} else if (csFilters.queryType == "State ID"){
			$scope.existingFilters.push("Task");
		} else if (csFilters.queryType != "Task ID"){
			$scope.existingFilters.push("Service", "State", "Task");
		}
		
		$scope.errorMsg = {};
		
		$timeout(function(){
	    	// fixes AMPMS undefined problem
	    	$scope.dateObj.fromDate = csFilters.fromDate; // custom range start date
			$scope.dateObj.toDate = csFilters.toDate; // custom range end date
	    }, 0 , false);
			
		$scope.cancel = function(){
		   $scope.$close();
		 };
	
		$scope.addFilter = function(){		
			csFilters.dateFilter = $scope.dateFilter;
			csFilters.statusFilter = $scope.statusFilter;
			csFilters.selectFilter = $scope.selectFilterModel;
			csFilters.typeFilter = $scope.typeFilter;
	        
			csFilters.fromDate = $scope.dateObj.fromDate;
			csFilters.toDate = 	$scope.dateObj.toDate;
			csFilters.dateFilterType = $scope.dateObj.dateFilterType;
			
			csFilters.filterString = $scope.createFilterString();
			csFilters.applyFilters();
			$scope.$close();
		};
		
		$scope.errorsExist = function () {
	    	for (var error in $scope.errorMsg) {
	    		if ($scope.errorMsg[error] !== ""){
	    			return true; 
	    		}
	    	}
	    	
	    };
	    
	    $scope.createFilterString = function () {
			// creates a string with filter information that shows up below the customerID. 
			var stringArray = [];
			var i = 0;
			
			if (csFilters.selectFilter !== $scope.existingFilters[0] && csFilters.typeFilter.length > 0 ){
				var itemString = csFilters.selectFilter + " Types - ";
				if (csFilters.typeFilter[0] != "Select All"){
					for (var j = 0; j < csFilters.typeFilter.length; j++){
						if (j < 3){
							itemString += csFilters.typeFilter[j];
						}
						if (csFilters.typeFilter[j+1] !== undefined && j < 3){
							itemString += ", "
						}
						if (j === 3 && csFilters.typeFilter[j] !== undefined){
							itemString += "and more "
								break;
						}
					}
				} else {
					itemString += "All";
				}
				stringArray[i] = itemString; 
				i++; 
			}
			
			// Append date filter if any
			if (csFilters.dateFilter === 'Custom Range' && (csFilters.toDate !== null || csFilters.fromDate !== null)){
				var dateString = csFilters.dateFilterType; 
		
				if (csFilters.fromDate !== null){
					var dateStartString = moment(csFilters.fromDate).format("DD.MM.YYYY");
				}
				
				if (csFilters.toDate !== null){
					var dateEndString = moment(csFilters.toDate).format("DD.MM.YYYY");
				}
				
				if (dateStartString && dateEndString)
					dateString += " between " + dateStartString + " - " + dateEndString;
				else if (dateStartString)
					dateString += " from " + dateStartString + " and after";
				else 
					dateString += " " + "Up to " + dateEndString; 
				
				if (dateString){
					stringArray[i] = dateString;
					i++;
				}
			}
			
			if (csFilters.dateFilter !== $scope.quickFilterCategories[0] && csFilters.dateFilter !== 'Custom Range'){
				stringArray[i] = csFilters.dateFilterType + " " + csFilters.dateFilter;
				i++; 
			}
			
			if (csFilters.statusFilter !== $scope.statusCategories[0]){
				stringArray[i] = csFilters.statusFilter;
				i++;
			}
			
			if (stringArray.length > 0 ) {
				var filterString = "";
				
				for (var i = 0; i < stringArray.length ; i++){
					filterString += stringArray[i];
					if (stringArray[i+1])
						filterString += "   |   "
				}
			}
			
			return filterString;
			
		};
		
		$scope.resetFilters = function() {
			csFilters.resetFilters();
			$scope.$close();
			
		};

	    $scope.$watch('dateObj.fromDate', function () {
	        if ($scope.dateObj.fromDate && $scope.dateObj.toDate && ($scope.dateObj.fromDate > $scope.dateObj.toDate)) {
	          $scope.errorMsg.date = "Please select valid date durations" 
	        }
	        else {
	            $scope.errorMsg.date = "";
	        }
	    }, true);

	    
	    $scope.$watch('dateObj.toDate', function () {
	        if ($scope.dateObj.fromDate && $scope.dateObj.toDate && ($scope.dateObj.fromDate > $scope.dateObj.toDate)) {
	          $scope.errorMsg.date = "Please select valid date durations" 
	        }
	        else {
	            $scope.errorMsg.date = "";
	        }
	    }, true);
	    
	    $scope.$watch('dateFilter', function (newValue, oldValue) {
	        if (newValue !== "Custom Range")
	            $scope.errorMsg.date = "";
	        else if ($scope.dateObj.fromDate && $scope.dateObj.toDate && ($scope.dateObj.fromDate > $scope.dateObj.toDate))
	        	$scope.errorMsg.date = "Please select valid date durations" 
	       
	    }, true);
	    
	    
	    $scope.$watch('selectFilterModel', function(newValue, oldValue) {
	    	if (newValue == 'Service'){
	    		$scope.typeFilterList = $scope.serviceTypes;
	    	} else if (newValue == 'State'){
	    		$scope.typeFilterList = $scope.stateTypes;
	    	} else if (newValue == 'Task'){
	    		$scope.typeFilterList = $scope.taskTypes;
	    	}
	    	
	    	if (oldValue != newValue){
	    		// Value changed
		    	$scope.typeFilter = ['Select All'];
		    	$scope.statusFilter = $scope.statusCategories[0];
				$scope.dateFilter = $scope.quickFilterCategories[0];
				$scope.dateObj.dateFilterType = $scope.filterByDateCategories[0];
			    $scope.dateObj.fromDate = null;
			    $scope.dateObj.toDate = null;
	    	}
    	}, true);
	    
	    $scope.$watch('typeFilter', function(newValue, oldValue) {
	    	// used to watch the filter select menu . If select all is clicked,
			// uncheck everything else.
	    	
	    	if (newValue.indexOf('Select All') !== -1 && newValue.length > 1) { // if 'Select All' is enabled
	            if (oldValue.indexOf('Select All') !== -1) { 
	            // if something was enabled after 'Select All' has been enabled
	            	var index = newValue.indexOf('Select All');
	              $scope.typeFilter.splice(index, 1); // deselect 'Select All'
	            }
	            else { // if 'Select All' is the most recent thing to be enabled
	              $scope.typeFilter = ['Select All']; // deselect everything else
	            }
	        }
	        if ($scope.selectFilterModel !== $scope.existingFilters[0] && $scope.typeFilter.length === 0){
	            $scope.errorMsg.typeFilter = $scope.selectFilterModel + " type cannot be blank"  
	        }
	        else {
	            $scope.errorMsg.typeFilter = ""   
	        }
	    }, true);
});