'use strict';

var EmployeeListCtrl = ['$scope', '$location', '$routeParams', 'employees', function ($scope, $location, $routeParams, employees) {
    $scope.search = $routeParams.q || '';
    $scope.info = employees;
    var re = /((([^ ]+):\s*('[^':]+'|"[^":]+"|[^ ]+))|[^ ]+[^: '"]*)/g;

    $scope.isTrue = function (value) {
        value = value.toLowerCase();
        return !_.any(['f', 'fa', 'fal', 'fals', 'false', 'n', 'no', '0'], function (item) {
            return item === value;
        });
    };

    $scope.$watch('search', function (newValue, oldValue) {
        $scope.filterEmployees(newValue);
    }, true);

    $scope.filterEmployees = _.debounce(function (q) {
        if (q !== $scope._search) {
            $scope._search = q;
            if (angular.isUndefined(q) || q === '') {
                $location.path('/Employees').search('q', null).replace();
            } else {
                $location.path('/Employees').search({'q': q}).replace();
            }
            $scope.$apply(function () {
                $scope.employees = $scope.doFilter(q);
            });
        }
    }, 350);
    $scope.doFilter = _.memoize(function (q) {
        var matches = [], i, len;
        if (angular.isUndefined(q) || q === '') {
            return $scope.info;
        }
        var m = q.match(re);
        _.forEach(m, function (item) {
            item = item.toLowerCase();
            if (item.indexOf(':') === -1) {
                matches.push({'key': 'n', 'value': item});
            } else {
                var key = item.substr(0, item.indexOf(':')).toLowerCase();
                var value = item.substr(item.indexOf(':') + 1, item.length).trim().toLowerCase();
                if (value.indexOf("'") === 0 || value.indexOf('"') === 0) {
                    value = value.substring(1, value.length - 2);
                }
                if (key !== '' && value !== '' && _.any(['w', 'dep', 'des', 'c'], function (item) {
                    return item === key;
                })) {
                    matches.push({'key': key, 'value': value});
                }
            }
        });
        return _.filter($scope.info, function (item) {
            len = matches.length;
            for (i = 0; i < len; i++) {
                var match = matches[i];
                if (match.key === 'n') {
                    if (item.Name.toLowerCase().indexOf(match.value) === -1) {
                        return false;
                    }
                } else if (match.key === 'w') {
                    if (item.IsActive !== $scope.isTrue(match.value)) {
                        return false;
                    }
                } else if (match.key === 'dep') {
                    if (item.CostCenter.toLowerCase().indexOf(match.value) === -1) {
                        return false;
                    }
                } else if (match.key === 'des') {
                    if (item.Designation.toLowerCase().indexOf(match.value) === -1) {
                        return false;
                    }
                } else if (match.key === 'c') {
                    if (item.Code.toString().indexOf(match.value) === -1) {
                        return false;
                    }
                }
            }
            return true;
        });
    });
}];

EmployeeListCtrl.resolve = {
    employees: ['Employee', function (Employee) {
        return Employee.query({}).$promise;
    }]
};

var EmployeeCtrl = ['$scope', '$routeParams', '$location', 'dateFilter', '$modal', 'employee', 'cost_centers', function ($scope, $routeParams, $location, dateFilter, $modal, employee, cost_centers) {
    $scope.employee = employee;

    $scope.cost_centers = cost_centers;

    $scope.save = function () {
        if (angular.isDate($scope.employee.JoiningDate)) {
            $scope.employee.JoiningDate = dateFilter($scope.employee.JoiningDate, 'dd-MMM-yyyy');
        }
        if (angular.isDate($scope.employee.LeavingDate)) {
            $scope.employee.LeavingDate = dateFilter($scope.employee.LeavingDate, 'dd-MMM-yyyy');
        }
        $scope.employee.$save(function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: u.Code});
            $location.path('/Employees');
        }, function (data, status) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

    $scope.delete = function () {
        $scope.employee.$delete(function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $location.path('/Employees');
        }, function (data, status) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

    $scope.confirm = function () {
        var modalInstance = $modal.open({
            backdrop: true,
            templateUrl: '/template/modal/confirm.html',
            controller: ['$scope', '$modalInstance', function ($scope, $modalInstance) {
                $scope.title = "Delete Account";
                $scope.body = "Are you sure? This cannot be undone.";
                $scope.isDelete = true;
                $scope.ok = function () {
                    $modalInstance.close();
                };
                $scope.cancel = function () {
                    $modalInstance.dismiss('cancel');
                };
            }]
        });
        modalInstance.result.then(function () {
            $scope.delete();
        });
    };

    $('#txtName').focus();
}];

EmployeeCtrl.resolve = {
    employee: ['$route', 'Employee', function ($route, Employee) {
        var id = $route.current.params.id;

        return Employee.get({id: id}).$promise;
    }],
    cost_centers: ['CostCenter', function (CostCenter) {
        return CostCenter.query({}).$promise;
    }]
};
