'use strict';

var PurchaseCtrl = ['$scope', '$location', 'dateFilter', '$modal', 'voucher', 'Account', 'Product', function ($scope, $location, dateFilter, $modal, voucher, Account, Product) {
    $scope.voucher = voucher;
    function getOldInventory(productID, inventories) {
        if (angular.isUndefined(productID)) {
            return;
        }
        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.product.ProductID, this.voucher.Inventories),
            quantity = Number($scope.quantity),
            tax = ($scope.tax) ? Number($scope.tax) : 0,
            discount = ($scope.discount) ? Number($scope.discount) : 0,
            price = Number($scope.product.Price);

        if (!$scope.product || !$scope.product.ProductID || !quantity || !price) {
            return;
        }

        if (typeof oldInventory === 'undefined') {
            this.voucher.Inventories.push(
                {
                    Product: $scope.product,
                    Quantity: quantity,
                    Rate: price,
                    Tax: tax,
                    Discount: discount,
                    Amount: quantity * price * (1 + tax) * (1 - discount)
                });
            delete $scope.product;
            delete $scope.quantity;
            delete $scope.tax;
            delete $scope.discount;
            $('#txtProduct').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'];
        } 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'}, function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $location.path('/Purchase/' + 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('/Purchase').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-modal.html',
            controller: PurchaseModalCtrl,
            resolve: {edit: function () {
                return edit;
            }}
        });
        modalInstance.result.then(function (updated) {
            if (updated.Product.ProductID !== $scope.selectedInventory.Product.ProductID) {
                var oldInventory = getOldInventory(updated.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.products = function ($viewValue) {
        return Product.autocomplete({term: $viewValue, count: 20, a: true}).$promise;
    };
}];

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

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

var PurchaseModalCtrl = ['$scope', '$modalInstance', 'edit', 'Product', function ($scope, $modalInstance, edit, Product) {
    $scope.edit = edit;
    $scope.ok = function () {
        $scope.edit.Quantity = Number(edit.Quantity);
        $scope.edit.Tax = ($scope.edit.Tax) ? Number($scope.edit.Tax) : 0;
        $scope.edit.Discount = ($scope.edit.Discount) ? Number($scope.edit.Discount) : 0;
        $scope.edit.Rate = Number($scope.edit.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.products = function ($viewValue) {
        return Product.autocomplete({term: $viewValue, count: 20}).$promise;
    };
}];
