'use strict';

var SalaryDeductionCtrl = ['$scope', '$location', 'dateFilter', '$modal', 'voucher', 'Employee', function ($scope, $location, dateFilter, $modal, voucher, Employee) {
    $scope.voucher = voucher;

    function getOldItem(ledgerID, items) {
        for (var i = 0, l = items.length; i < l; i++) {
            if (items[i].Journal.Ledger.LedgerID === ledgerID) {
                return items[i];
            }
        }
    }

    function daysInMonthFunction(date) {
        if (angular.isDate(date)) {
            return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
        }

        var months = {
            Jan: 1,
            Feb: 2,
            Mar: 3,
            Apr: 4,
            May: 5,
            Jun: 6,
            Jul: 7,
            Aug: 8,
            Sep: 9,
            Oct: 10,
            Nov: 11,
            Dec: 12
        };
        if (!date.match(/^\d{2}-[\w]{3}-[\d]{4}$/g)) {
            return;
        }
        var parts = date.split("-");
        return new Date(parseInt(parts[2], 10), months[parts[1]], 0).getDate();
    }

    function getEsi(grossSalary, daysWorked, daysInMonth) {
        var limit = 15000,
            employee_rate = 0.0175,
            employer_rate = 0.0475,
            employee = (grossSalary > limit) ? 0 : Math.ceil(employee_rate * grossSalary * daysWorked / daysInMonth),
            employer = (grossSalary > limit) ? 0 : Math.ceil(employer_rate * grossSalary * daysWorked / daysInMonth);
        return {ee: employee, er: employer, both: employee + employer};
    }

    function getPf(grossSalary, daysWorked, daysInMonth) {
        var limit = 6500,
            employee_rate = 0.12,
            employer_rate = 0.12 + 0.011 + 0.005 + 0.0001,
            employee = (grossSalary > limit) ? 0 : Math.ceil(employee_rate * grossSalary * daysWorked / daysInMonth),
            employer = (grossSalary > limit) ? 0 : Math.ceil(employer_rate * grossSalary * daysWorked / daysInMonth);
        return {ee: employee, er: employer, both: employee + employer};
    }

    $scope.add = function () {
        var oldJournal = getOldItem($scope.employee.LedgerID, this.voucher.SalaryDeductions),
            grossSalary = parseInt($scope.grossSalary, 10),
            daysWorked = parseInt($scope.daysWorked, 10),
            daysInMonth = daysInMonthFunction($scope.voucher.Date),
            esi = getEsi(grossSalary, daysWorked, daysInMonth),
            pf = getPf(grossSalary, daysWorked, daysInMonth);

        if (typeof oldJournal !== 'undefined') {
            $scope.toasts.push({Type: 'Danger', Message: 'Employee has already been added!'});
        } else {
            this.voucher.SalaryDeductions.push({
                Journal: {Ledger: $scope.employee},
                GrossSalary: grossSalary,
                DaysWorked: daysWorked,
                EsiEmployee: esi.ee,
                PfEmployee: pf.ee,
                EsiEmployer: esi.er,
                PfEmployer: pf.er
            });
        }
        delete $scope.employee;
        delete $scope.grossSalary;
        delete $scope.daysWorked;
        $('#txtEmployee').focus();
    };

    $scope.remove = function (deduction) {
        var index = this.voucher.SalaryDeductions.indexOf(deduction);
        this.voucher.SalaryDeductions.splice(index, 1);
    };

    $scope.preventAlteration = function (voucher) {
        if (typeof $scope.perms === 'undefined') {
            return false;
        } else if (typeof voucher.VoucherID === 'undefined') {
            return !$scope.perms['Salary Deduction'];
        } else if (voucher.Posted && !$scope.perms['Edit Posted Vouchers']) {
            return true;
        } else if (voucher.User.UserID != $scope.auth.UserID && !$scope.perms["Edit Other User's Vouchers"]) {
            return true;
        } else {
            return false;
        }
    };

    $scope.get = function (voucherid) {
        $scope.voucher = Voucher.get({VoucherID: voucherid}, function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
        }, function (data, status) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

    $scope.save = function () {
        if (angular.isDate($scope.voucher.Date)) {
            $scope.voucher.Date = dateFilter($scope.voucher.Date, 'dd-MMM-yyyy');
        }
        $scope.voucher.$save({type: 'Salary Deduction'}, function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $location.path('/SalaryDeduction/' + u.VoucherID);
        }, function (data, status) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

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

    $scope.post = function () {
        $scope.voucher.$post(function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
        }, 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 Voucher";
                $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();
        });
    };

    $scope.employees = function ($viewValue) {
        return Employee.autocomplete({term: $viewValue, count: 20}).$promise;
    };
}];


SalaryDeductionCtrl.resolve = {
    voucher: ['$route', 'Voucher', function ($route, Voucher) {
        var id = $route.current.params.id;

        if (typeof id === 'undefined') {
            return Voucher.get({type: 'Salary Deduction'}).$promise;
        } else {
            return Voucher.get({id: id}).$promise;
        }
    }]
};
