'use strict';

function IssueCtrl($scope, $routeParams, $location, voucher, cost_centers, issue_grid, IssueGrid, Voucher) {
    $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.addInventory = 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 (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').val('');
            $('#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').val('');
            $('#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) {
        if (newDate !== oldDate && typeof newDate !== 'undefined') {
            if (typeof $routeParams.Source !== 'undefined' && typeof $routeParams.Destination !== 'undefined' && typeof $routeParams.id !== 'undefined') {
                $location.path('/Issue/' + newDate).search({Source:$routeParams.Source, Destination:$routeParams.Destination});
            } else {
                $scope.smallGrid = IssueGrid.query({date:newDate, 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 (var i = 0, l = $scope.voucher.Journals.length; i < l; i++) {
            $scope.voucher.Journals[i].Amount = amount;
        }
    }, true);

    $scope.resetVoucher = function (voucherid) {
        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:'Error', Message:data.data});
        });
    };

    $scope.save = function () {
        $scope.voucher.$save({type:'Issue'}, function (u, putResponseHeaders) {
            $scope.toasts.push({Type:'Success', Message:''});
            $scope.redirectOnSave(u);
        }, function (data, status) {
            $scope.toasts.push({Type:'Error', Message:data.data});
        });
    };

    $scope.delete = function () {
        $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:'Error', 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.toggleEdit = function (inventory, update) {
        if (typeof update === 'undefined') {
            $scope.edit = {};
            angular.copy(inventory, $scope.edit);
        } else {
            if (update === true && typeof $scope.edit !== 'undefined') {
                var edit = $scope.edit;
                if (inventory.Product.ProductID !== edit.Batch.Product.ProductID) {
                    var oldInventory = getOldInventory(edit.Batch.Product.ProductID, $scope.voucher.Inventories);
                    if (typeof oldInventory !== 'undefined') {
                        return false;
                    }
                }
                edit.Product = edit.Batch.Product;
                edit.Quantity = Number(edit.Quantity);
                edit.Tax = edit.Batch.Tax;
                edit.Discount = edit.Batch.Discount;
                edit.Rate = edit.Batch.Rate;
                edit.Amount = edit.Quantity * edit.Rate * (1 + edit.Tax) * (1 - edit.Discount);
                angular.copy(edit, inventory);
                $scope.$apply();
                return true;
            } else if (update === false) {
                delete $scope.edit;
            }
        }
    };
}

IssueCtrl.resolve = {
    voucher:function ($q, $route, Voucher) {
        var deferred = $q.defer();

        var id = $route.current.params.id;
        var source = $route.current.params.Source;
        var destination = $route.current.params.Destination;

        var successCb = function (result) {
            deferred.resolve(result);
        };

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

        var id = $route.current.params.id;
        var source = $route.current.params.Source;
        var destination = $route.current.params.Destination;

        var successCb = function (result) {
            deferred.resolve(result);
        };

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

        var successCb = function (result) {
            deferred.resolve(result);
        };

        CostCenter.query({}, successCb);
        return deferred.promise;
    }
};