'use strict';

var IssueCtrl = ['$scope', '$routeParams', '$location', 'dateFilter', 'voucher', 'cost_centers', 'issue_grid', 'IssueGrid', 'Voucher', '$modal', 'Batch', function ($scope, $routeParams, $location, dateFilter, voucher, cost_centers, issue_grid, IssueGrid, Voucher, $modal, Batch) {
    $scope.voucher = voucher;
    $scope.cost_centers = cost_centers;
    $scope.smallGrid = issue_grid;

    if (typeof $routeParams.Source === 'undefined' && typeof $routeParams.Destination === 'undefined' && typeof $routeParams.id === 'undefined') {
        var date = $scope.voucher.Date;
        var source = getDebitCredit($scope.voucher.Journals, -1);
        var destination = getDebitCredit($scope.voucher.Journals, 1);
        $location.path('/Issue/' + date).search({Source: source, Destination: destination});
    }

    function getOldInventory(productID, inventories) {
        for (var i = 0, l = inventories.length; i < l; i++) {
            if (inventories[i].Product.ProductID === productID) {
                return inventories[i];
            }
        }
    }

    $scope.add = function () {
        var oldInventory = getOldInventory($scope.batch.Product.ProductID, this.voucher.Inventories),
            quantity = Number($scope.quantity),
            consumption = (getDebitCredit($scope.voucher.Journals, -1) === '7b845f95-dfef-fa4a-897c-f0baf15284a3');

        if (!$scope.batch || !$scope.batch.Product.ProductID || !quantity) {
            return;
        }

        if (typeof oldInventory !== 'undefined' &&
            oldInventory.Batch.BatchID === $scope.batch.BatchID &&
            (!consumption || oldInventory.Quantity + quantity <= $scope.batch.QuantityRemaining)) {
            oldInventory.Quantity += quantity;
            delete $scope.batch;
            delete $scope.quantity;
            $('#txtBatch').focus();
        }

        if (typeof oldInventory === 'undefined' && (!consumption || quantity <= $scope.batch.QuantityRemaining)) {
            this.voucher.Inventories.push(
                {
                    Product: $scope.batch.Product,
                    Quantity: quantity,
                    Rate: $scope.batch.Rate,
                    Tax: $scope.batch.Tax,
                    Discount: $scope.batch.Discount,
                    Amount: quantity * $scope.batch.Rate * (1 + $scope.batch.Tax) * (1 - $scope.batch.Discount),
                    Batch: $scope.batch
                });
            delete $scope.batch;
            delete $scope.quantity;
            $('#txtBatch').focus();
        }
    };
    $scope.removeInventory = function (inventory) {
        var index = this.voucher.Inventories.indexOf(inventory);
        this.voucher.Inventories.splice(index, 1);
    };

    $scope.$watch('voucher.Date', function (newDate, oldDate) {
        var nDate = angular.isDate(newDate) ? dateFilter(newDate, 'dd-MMM-yyyy') : newDate,
            oDate = angular.isDate(oldDate) ? dateFilter(oldDate, 'dd-MMM-yyyy') : oldDate;


        if (nDate !== oDate && typeof nDate !== 'undefined') {
            if (typeof $routeParams.Source !== 'undefined' && typeof $routeParams.Destination !== 'undefined' && typeof $routeParams.id !== 'undefined') {
                $location.path('/Issue/' + nDate).search({Source: $routeParams.Source, Destination: $routeParams.Destination});
            } else {
                $scope.smallGrid = IssueGrid.query({date: nDate, Source: $routeParams.Source, Destination: $routeParams.Destination});
            }
        }
    }, true);

    function getDebitCredit(journals, type) {
        for (var i = 0, l = journals.length; i < l; i++) {
            if (journals[i].Debit === type) {
                return journals[i].CostCenter.CostCenterID;
            }
        }
    }

    $scope.$watch('voucher.Journals', function (newJournals, oldJournals) {
        if (typeof newJournals === 'undefined' || angular.equals(newJournals, oldJournals)) {
            return;
        }
        if (typeof oldJournals !== 'undefined') {
            if (getDebitCredit(oldJournals, -1) === getDebitCredit(newJournals, -1) && getDebitCredit(oldJournals, 1) === getDebitCredit(newJournals, 1)) {
                return;
            }
        }

        if (typeof $routeParams.Source !== 'undefined' && typeof $routeParams.Destination !== 'undefined' && typeof $routeParams.id !== 'undefined') {
            $location.path('/Issue/' + $scope.voucher.Date).search({Source: getDebitCredit(newJournals, -1), Destination: getDebitCredit(newJournals, 1)});
        } else {
            $scope.smallGrid = IssueGrid.query({date: $scope.voucher.Date, Source: getDebitCredit(newJournals, -1), Destination: getDebitCredit(newJournals, 1)});
        }
    }, true);

    $scope.$watch('voucher.Inventories', function (newInventories, oldInventories) {
        if (typeof newInventories === 'undefined' || typeof oldInventories === 'undefined') {
            return;
        }
        var amount = 0;
        for (var i = 0, l = newInventories.length; i < l; i++) {
            amount += newInventories[i].Amount;
        }
        for (i = 0, l = $scope.voucher.Journals.length; i < l; i++) {
            $scope.voucher.Journals[i].Amount = amount;
        }
    }, true);

    $scope.resetVoucher = function () {
        var date = $scope.voucher.Date;
        var source = getDebitCredit($scope.voucher.Journals, -1);
        var destination = getDebitCredit($scope.voucher.Journals, 1);
        $location.path('/Issue/' + date).search({Source: source, Destination: destination});
    };

    $scope.preventAlteration = function (voucher) {
        if (typeof voucher.VoucherID === 'undefined') {
            return !$scope.perms['Issue'];
        } 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({id: voucherid}, function (u, putResponseHeaders) {
            $location.path('/Issue/' + u.VoucherID);
        }, 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: 'Issue'}, function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $scope.redirectOnSave(u);
        }, function (data, status) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

    $scope.delete = function () {
        return $scope.voucher.$delete(function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            var date = u.Date;
            var source = getDebitCredit(u.Journals, -1);
            var destination = getDebitCredit(u.Journals, 1);
            $location.path('/Issue/' + date).search({Source: source, Destination: destination}).replace();
        }, function (data, status) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };
    $scope.redirectOnSave = function (voucher) {
        if (typeof $routeParams.Source !== 'undefined' && typeof $routeParams.Destination !== 'undefined' && typeof $routeParams.id !== 'undefined') {
            Voucher.get({type: 'Issue', Date: $routeParams.id, Source: $routeParams.Source, Destination: $routeParams.Destination}, function (u, putResponseHeaders) {
                $scope.voucher = u;
            });
            $scope.smallGrid = IssueGrid.query({date: $routeParams.id, Source: $routeParams.Source, Destination: $routeParams.Destination});
        } else {
            var date = voucher.Date;
            var source = getDebitCredit(voucher.Journals, -1);
            var destination = getDebitCredit(voucher.Journals, 1);
            $location.path('/Issue/' + date).search({Source: source, Destination: destination});
        }
    };

    $scope.modal = function (inventory) {
        $scope.selectedInventory = inventory;
        var edit = {};
        angular.copy($scope.selectedInventory, edit);
        var modalInstance = $modal.open({
            backdrop: true,
            templateUrl: '/partial/issue-modal.html',
            controller: IssueModalCtrl,
            resolve: {edit: function () {
                return edit;
            }}
        });
        modalInstance.result.then(function (updated) {
            if (updated.Product.ProductID !== $scope.selectedInventory.Batch.Product.ProductID) {
                var oldInventory = getOldInventory(updated.Batch.Product.ProductID, $scope.voucher.Inventories);
                if (typeof oldInventory !== 'undefined') {
                    delete $scope.selectedInventory;
                    return false;
                }
            }
            angular.copy(updated, $scope.selectedInventory);
            delete $scope.selectedInventory;
        }, function () {
            delete $scope.selectedInventory;
        });
    };

    $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 () {
            return $scope.delete();
        });
        return modalInstance;
    };

    $scope.batches = function ($viewValue) {
        var params = {term: $viewValue, count: 20};
        if (angular.isDate($scope.voucher.Date)) {
            params.date = dateFilter($scope.voucher.Date, 'dd-MMM-yyyy');
        } else {
            params.date = $scope.voucher.Date;
        }
        return Batch.autocomplete(params).$promise;
    };
}];

IssueCtrl.resolve = {
    voucher: ['$route', 'Voucher', function ($route, Voucher) {
        var id = $route.current.params.id,
            source = $route.current.params.Source,
            destination = $route.current.params.Destination;

        if (typeof source !== 'undefined' && typeof destination !== 'undefined' && typeof id !== 'undefined') {
            return Voucher.get({type: 'Issue', Date: id, Source: source, Destination: destination}).$promise;
        } else if (typeof source === 'undefined' && typeof destination === 'undefined' && typeof id !== 'undefined') {
            return Voucher.get({id: id}).$promise;
        } else {
            return Voucher.get({type: 'Issue'}).$promise;
        }
    }],
    issue_grid: ['$route', 'IssueGrid', function ($route, IssueGrid) {
        var id = $route.current.params.id,
            source = $route.current.params.Source,
            destination = $route.current.params.Destination;

        if (typeof source !== 'undefined' && typeof destination !== 'undefined' && typeof id !== 'undefined') {
            return IssueGrid.query({date: id, Source: source, Destination: destination}).$promise;
        } else if (typeof source === 'undefined' && typeof destination === 'undefined' && typeof id !== 'undefined') {
            return IssueGrid.query({date: id}).$promise;
        } else {
            return [];
        }
    }],
    cost_centers: ['CostCenter', function (CostCenter) {
        return CostCenter.query({}).$promise;
    }]
};

var IssueModalCtrl = ['$scope', '$modalInstance', 'edit', 'Batch', function ($scope, $modalInstance, edit, Batch) {
    $scope.edit = edit;
    $scope.ok = function () {
        $scope.edit.Product = $scope.edit.Batch.Product;
        $scope.edit.Quantity = Number($scope.edit.Quantity);
        $scope.edit.Tax = $scope.edit.Batch.Tax;
        $scope.edit.Discount = $scope.edit.Batch.Discount;
        $scope.edit.Rate = $scope.edit.Batch.Rate;
        $scope.edit.Amount = $scope.edit.Quantity * $scope.edit.Rate * (1 + $scope.edit.Tax) * (1 - $scope.edit.Discount);
        $modalInstance.close($scope.edit);
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
    $scope.batches = function ($viewValue) {
        return Batch.autocomplete({term: $viewValue, count: 20}).$promise;
    };
}];