'use strict';

var IssueController = ['$scope', '$routeParams', '$location', 'asDateFilter', 'voucher', 'costCentres', 'smallGrid', 'IssueGrid', 'Voucher', '$modal', 'Batch', function ($scope, $routeParams, $location, asDate, voucher, costCentres, smallGrid, IssueGrid, Voucher, $modal, Batch) {
    $scope.voucher = voucher;
    $scope.costCentres = costCentres;
    $scope.smallGrid = smallGrid;

    if (angular.isUndefined($routeParams.Source) && angular.isUndefined($routeParams.Destination) && angular.isUndefined($routeParams.id)) {
        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 getOld(productID, inventories) {
        return _.find(inventories, function (inventory) {
            return inventory.Product.ProductID === productID;
        });
    }

    $scope.add = function () {
        var oldInventory = getOld($scope.batch.Product.ProductID, $scope.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 (!angular.isUndefined(oldInventory) &&
            oldInventory.Batch.BatchID === $scope.batch.BatchID &&
            (!consumption || oldInventory.Quantity + quantity <= $scope.batch.QuantityRemaining)) {
            oldInventory.Quantity += quantity;
            delete $scope.batch;
            delete $scope.quantity;
            $scope.foBatch = true;
        }

        if (angular.isUndefined(oldInventory) && (!consumption || quantity <= $scope.batch.QuantityRemaining)) {
            $scope.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;
            $scope.foBatch = true;
        }
    };
    $scope.removeInventory = function (inventory) {
        var index = $scope.voucher.Inventories.indexOf(inventory);
        $scope.voucher.Inventories.splice(index, 1);
    };

    $scope.$watch('voucher.Date', function (newDate, oldDate) {
        var nDate = asDate(newDate),
            oDate = asDate(oldDate);


        if (nDate !== oDate && !angular.isUndefined(nDate)) {
            if (!angular.isUndefined($routeParams.Source) && !angular.isUndefined($routeParams.Destination) && !angular.isUndefined($routeParams.id)) {
                $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].CostCentre.CostCentreID;
            }
        }
    }

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

        if (!angular.isUndefined($routeParams.Source) && !angular.isUndefined($routeParams.Destination) && !angular.isUndefined($routeParams.id)) {
            $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 (angular.isUndefined(newInventories) || angular.isUndefined(oldInventories)) {
            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 (angular.isUndefined(voucher.VoucherID)) {
            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 () {
        $scope.voucher.Date = asDate($scope.voucher.Date);
        $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 (!angular.isUndefined($routeParams.Source) && !angular.isUndefined($routeParams.Destination) && !angular.isUndefined($routeParams.id)) {
            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,
            size: 'lg',
            templateUrl: '/partial/issue-modal.html',
            controller: IssueModalController,
            resolve: {
                edit: function () {
                    return edit;
                }
            }
        });
        modalInstance.result.then(function (updated) {
            if (updated.Product.ProductID !== $scope.selectedInventory.Batch.Product.ProductID) {
                var oldInventory = getOld(updated.Batch.Product.ProductID, $scope.voucher.Inventories);
                if (!angular.isUndefined(oldInventory)) {
                    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, date: asDate($scope.voucher.Date)};
        return Batch.autocomplete(params).$promise;
    };
}];

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

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

        if (!angular.isUndefined(source) && !angular.isUndefined(destination) && !angular.isUndefined(id)) {
            return IssueGrid.query({date: id, Source: source, Destination: destination}).$promise;
        } else if (angular.isUndefined(source) && angular.isUndefined(destination) && !angular.isUndefined(id)) {
            return IssueGrid.query({date: id}).$promise;
        } else {
            return [];
        }
    }],
    costCentres: ['CostCentre', function (CostCentre) {
        return CostCentre.query({}).$promise;
    }]
};

var IssueModalController = ['$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;
    };
}];