(function(){
'use strict';
  function transferControlSearchForm(FreightsAPI, ServiceCentersAPI, ReceptionCentersAPI,
  																	 Authentication, $q, DateUtilities) {

    function link($scope, $element, $attrs) {

    	$scope.currentUserRole = Authentication.user.role.name;
    	$scope.transferControlSearch = {};
    	var BIG_INTEGER_LIMIT = 2147483647;

    	$scope.isInvalidFolioFromForm = function() {
    		$scope.isFolioExisting = $scope.transferControlSearch.id ? true : false;

    		if($scope.transferControlSearch.id > BIG_INTEGER_LIMIT){
    			$scope.isInvalidFolio = true;
	    		return true;
    		}
    		$scope.isInvalidFolio = false;
    		return false;
    	};

    	var statusOptions = {
      	empleado_centro_recepcion: {
	      	'A recibir': {
	      		status: 'nuevo',
	      		destinationType: 'centro_recepcion'
	      	},
	      	Enviado: {
	      		status: 'nuevo',
	      		destinationType: 'centro_servicio'
	      	},
	      	Recibido: {
	      		status: 'recibido',
	      		destinationType: 'centro_recepcion'
	      	},
	      	'En servicio': {
	      		status: 'recibido',
	      		destinationType: 'centro_servicio'
	      	}
	      },
	      empleado_centro_servicio: {
	      	'A recibir': {
		      	status: 'nuevo',
		      	destinationType: 'centro_servicio'
		      },
		      'Enviado': {
		      	status: 'nuevo',
		      	destinationType: 'centro_recepcion'
		      },
		      'Recibido': {
		      	status: 'recibido',
		      	destinationType: 'centro_servicio'
		      },
		      'En servicio': {
		      	status: 'recibido',
		      	destinationType: 'centro_recepcion'
		      }
	      },
	      admin: {
	      	Nuevo: {
	      		status: 'nuevo'
	      	},
    			Recibido: {
    				status: 'recibido'
    			}
	      }
	    };

    	var defaultStatuses = [
    		'A recibir',
    		'Enviado',
    		'Recibido',
    		'En servicio',
    		'Incompleto',
    		'En traslado',
    		'Cancelado'
    	];

    	var AdminStatuses = [
    		'Nuevo',
    		'Recibido',
    		'Incompleto',
    		'En traslado',
    		'Cancelado'
    	];

    	if(Authentication.user.role.name === 'admin')
    		$scope.statuses = AdminStatuses;
    	else
    		$scope.statuses = defaultStatuses;

    	$scope.searchInputTranslations = {
        reset: 'Limpiar',
        search: 'Buscar...',
        nothingSelected: ''
      };

      $scope.selectedServiceCenter = [];
      $scope.selectedReceptionCenter = [];

      $scope.onServiceCenterChange = function() {
    		$scope.transferControlSearch.serviceCenterId = _.first($scope.selectedServiceCenter).id;
    	};

    	$scope.onServiceCenterReset = function() {
    		$scope.serviceCenters.forEach(function(serviceCenter) {
          serviceCenter.isChecked = false;
        });
    		$scope.transferControlSearch.serviceCenterId = null;
    	};

    	$scope.onReceptionCenterChange = function() {
    		$scope.transferControlSearch.receptionCenterId = _.first($scope.selectedReceptionCenter).id;
    	};

    	$scope.onReceptionCenterReset = function() {
    		$scope.receptionCenters.forEach(function(receptionCenter) {
          receptionCenter.isChecked = false;
        });
    		$scope.transferControlSearch.receptionCenterId = null;
    	};

    	var fetchFreight = function() {
    		FreightsAPI.fetchActives({}).$promise
    		.then(function(freights) {
    			$scope.freights = freights;
    		})
    		.catch(function(err) {
    			Materialize.toast('Error al obtener fletes', 4000);
    		});
    	};

    	var fetchServiceCenters = function() {
    		ServiceCentersAPI.fetchActives({}).$promise
    		.then(function(serviceCenters) {
    			$scope.serviceCenters = serviceCenters;
    		})
    		.catch(function(err) {
    			Materialize.toast('Error al obtener centros de servicio', 4000);
    		});
    	};

    	var fetchReceptionCenters = function() {
    		ReceptionCentersAPI.fetchActives({}).$promise
    		.then(function(receptionCenters) {
    			$scope.receptionCenters = receptionCenters;
    		})
    		.catch(function(err) {
    			Materialize.toast('Error al obtener centros de recepción', 4000);
    		});
    	};

    	var getTransferControls = function(transferControlsFilter) {
	      var deferred = $q.defer();

	      $scope.ngResource.query(
	        transferControlsFilter
	      ).$promise
	      .then(function(transferControls) {
	      	deferred.resolve(transferControls);
	      });

	      return deferred.promise;
	    };

	    var getCountOfTransferControls = function(transferControlsFilter) {
	      var deferred = $q.defer();

	      transferControlsFilter = _.omit(transferControlsFilter.filter, ['limit', 'skip', 'order', 'include']);

	      $scope.ngResource.count(
	        transferControlsFilter
	      ).$promise
	      .then(function(total) {
	         deferred.resolve(total);
	      });

	      return deferred.promise;
	    };

	    var fetchCountAndTransferControls = function(transferControlsFilter) {
	    	transferControlsFilter = setCurrentCenterInFilter(transferControlsFilter);

	      getCountOfTransferControls(transferControlsFilter)
	      .then(function(total) {
	        $scope.paginatorOptions.totalItems = total.count;
	      })
	      .catch(function(err) {
	      	Materialize.toast('Error al obtener contador de controles de transferencias', 4000);
	      });

	      _.extend(transferControlsFilter.filter, angular.copy($scope.searcherOptions.staticParams.filter));

	      getTransferControls(transferControlsFilter)
	      .then(function(transferControls) {
	      	$scope.sharedParams.where = transferControlsFilter.filter.where;
	      	$scope.paginatorOptions.page = 1;
	        $scope.items = transferControls;
	      })
	      .catch(function(err) {
	      	Materialize.toast('Error al obtener controles de transferencias', 4000);
	      });
	    };

	    var setCurrentCenterInFilter = function(transferControlsFilter) {
	    	if(Authentication.user.receptionCenterId)
	    		transferControlsFilter.filter.where.receptionCenterId = Authentication.user.receptionCenterId;

	    	if(Authentication.user.serviceCenterId)
	    		transferControlsFilter.filter.where.serviceCenterId = Authentication.user.serviceCenterId;

	    	return transferControlsFilter;
	    };

	    var setStatusFilterByStatus = function(transferControlsFilter, status) {
	    	if(status === 'Incompleto')
	        transferControlsFilter.filter.where.status = 'recibido_parcialmente';

	      if(status === 'En traslado')
	        transferControlsFilter.filter.where.status = 'traslado';

	      if(status === 'Cancelado')
	        transferControlsFilter.filter.where.status = 'cancelado';

	      if(transferControlsFilter.filter.where.status)
	      	return transferControlsFilter;

	      var roleName = Authentication.user.role.name;

	      if(roleName === 'admin'){
	      	 transferControlsFilter.filter.where.status =
		      	statusOptions.admin[status].status;
		      return transferControlsFilter;
	      }

	      if(roleName === 'empleado_centro_recepcion' ||
           roleName === 'jefe_centro_recepcion') {
		      transferControlsFilter.filter.where.status =
		      	statusOptions.empleado_centro_recepcion[status].status;
		      transferControlsFilter.filter.where.destinationType =
		      	statusOptions.empleado_centro_recepcion[status].destinationType;
		      return transferControlsFilter;
		    }

	      if(roleName === 'empleado_centro_servicio' ||
           roleName === 'jefe_centro_servicio'){
	      	transferControlsFilter.filter.where.status =
	      		statusOptions.empleado_centro_servicio[status].status;
	      	transferControlsFilter.filter.where.destinationType =
		      	statusOptions.empleado_centro_servicio[status].destinationType;
		    }

	      return transferControlsFilter;
	    };

	    var getTransferControlFilter = function() {
	      var transferControlsFilter = {filter: {where: {}, limit:20} };

	      if($scope.transferControlSearch.status)
	      	transferControlsFilter = setStatusFilterByStatus(transferControlsFilter,
	      																									 $scope.transferControlSearch.status);

	      if($scope.transferControlSearch.startDate && $scope.transferControlSearch.endDate)
	        transferControlsFilter.filter.where.createdAt = {
	        	between: [DateUtilities.addTimezoneOffsetToDate($scope.transferControlSearch.startDate),
	        						DateUtilities.addTimezoneOffsetToEndDate($scope.transferControlSearch.endDate)]
	        };

	      if($scope.transferControlSearch.startDate && !$scope.transferControlSearch.endDate)
	        transferControlsFilter.filter.where.createdAt = {gte: DateUtilities.addTimezoneOffsetToDate($scope.transferControlSearch.startDate)};

	      if($scope.transferControlSearch.endDate && !$scope.transferControlSearch.startDate)
	        transferControlsFilter.filter.where.createdAt = {lte: DateUtilities.addTimezoneOffsetToEndDate($scope.transferControlSearch.endDate)};

	      if($scope.transferControlSearch.serviceCenterId)
	        transferControlsFilter.filter.where.serviceCenterId = $scope.transferControlSearch.serviceCenterId;

	      if($scope.transferControlSearch.receptionCenterId)
	        transferControlsFilter.filter.where.receptionCenterId = $scope.transferControlSearch.receptionCenterId;

	      if($scope.transferControlSearch.freightId)
	        transferControlsFilter.filter.where.freightId = $scope.transferControlSearch.freightId;

	      return transferControlsFilter;
	    };

	    var searchTransferControlById = function() {
	    	var transferControlByIdFilter = {
        	filter: {
        		where: {
        			id: $scope.transferControlSearch.id
        		}
        	}
        };

	      fetchCountAndTransferControls(transferControlByIdFilter);
	    };

    	$scope.searchTransferControls = function() {
	      if($scope.transferControlSearch.id)
	      	return searchTransferControlById();
	      
	      fetchCountAndTransferControls(getTransferControlFilter());
	    };

	    $scope.clearSearchForm = function() {
	    	var emptyTransferControlSearch = {
	    		id: null,
	    		startDate: null,
	    		endDate: null,
	    		status: null,
	    		freightId: null,
	    		receptionCenterId: null,
	    		serviceCenterId: null
	    	};
	    	$scope.onServiceCenterReset();
	    	$scope.onReceptionCenterReset();
	    	_.extend($scope.transferControlSearch, emptyTransferControlSearch);
    		$scope.searchTransferControls();
    	};
    	
	    fetchFreight();
	    fetchServiceCenters();
	    fetchReceptionCenters();
    }

    return {
      restrict: 'E',
      scope: {
        items: '=',
        paginatorOptions: '=',
        ngResource: '=',
        searcherOptions: '=',
        sharedParams: '='
      },
      templateUrl:'modules/core/views/transfer-control-list-custom-searcher.client.view.html',
      link: link
    };
  }

  angular.module('core').directive('transferControlSearchForm', [
  	'FreightsAPI',
  	'ServiceCentersAPI',
  	'ReceptionCentersAPI',
  	'Authentication',
  	'$q',
  	'DateUtilities',
    transferControlSearchForm
  ]);
})();