'use strict';

var PurchaseReturnCtrl = ['$scope', '$location', 'dateFilter', '$modal', 'voucher', 'Account', 'Batch', function ($scope, $location, dateFilter, $modal, voucher, Account, Batch) {
    $scope.voucher = voucher;
    $scope.rate = 0;
    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);

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

        if (typeof oldInventory === 'undefined' && 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.Inventories', function (inventories, oldValue) {
        var amount = 0;
        if (typeof inventories !== 'undefined') {
            for (var i = 0, l = inventories.length; i < l; i++) {
                amount += Number(inventories[i].Amount);
            }
        }
        if (typeof $scope.voucher.Journals !== 'undefined') {
            for (var i = 0, l = $scope.voucher.Journals.length; i < l; i++) {
                if ($scope.voucher.Journals[i].Debit === 1) {
                    $scope.voucher.Journals[i].Amount = amount;
                    break;
                }
            }
        }
    }, true);

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

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

    $scope.modal = function (inventory) {
        $scope.selectedInventory = inventory;
        var edit = {};
        angular.copy($scope.selectedInventory, edit);
        var modalInstance = $modal.open({
            backdrop: true,
            templateUrl: '/partial/purchase-return-modal.html',
            controller: PurchaseReturnModalCtrl,
            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 () {
            $scope.delete();
        });
    };

    $scope.accounts = function ($viewValue) {
        return Account.autocomplete({term: $viewValue, count: 20, a:true}).$promise;
    };
    $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;
    };
}];

PurchaseReturnCtrl.resolve = {
    voucher: ['$route', 'Voucher', function ($route, Voucher) {
        var id = $route.current.params.id;
        if (typeof id === 'undefined') {
            return Voucher.get({type: 'Purchase Return'}).$promise;
        } else {
            return Voucher.get({id: id}).$promise;
        }
    }]
};


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