'use strict';

var PurchaseReturnController = ['$scope', '$location', 'asDateFilter', '$modal', 'uploadedImageResizer', 'voucher', 'Account', 'Batch', function ($scope, $location, asDate, $modal, uploadedImageResizer, voucher, Account, Batch) {
    $scope.voucher = voucher;
    $scope.rate = 0;
    function getOld(productID, inventories) {
        return _.find(inventories, function (inventory) {
            return inventory.Product.ProductID === productID;
        });
    }

    $scope.$on("fileSelected", function (event, args) {
        uploadedImageResizer(args, $scope.voucher.Files);
    });


    $scope.deleteFile = function (item) {
        var index = $scope.voucher.Files.indexOf(item);
        $scope.voucher.Files.splice(index, 1);
    };

    $scope.zoomImage = function (item) {
        $modal.open({
            templateUrl: '/template/modal/image.html',
            controller: ['$scope', '$modalInstance', function ($scope, $modalInstance) {
                $scope.imageUrl = item.Resized;
                $scope.size = null;
                $scope.cancel = function () {
                    $modalInstance.dismiss('cancel');
                };
            }]
        });
    };

    $scope.add = function () {
        var oldInventory = getOld($scope.batch.Product.ProductID, $scope.voucher.Inventories),
            quantity = Number($scope.quantity);

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

        if (angular.isUndefined(oldInventory) && 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.Inventories', function (inventories) {
        var amount = 0,
            i,
            l;
        if (!angular.isUndefined(inventories)) {
            for (i = 0, l = inventories.length; i < l; i++) {
                amount += Number(inventories[i].Amount);
            }
        }
        if (!angular.isUndefined($scope.voucher.Journals)) {
            for (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 (angular.isUndefined($scope.perms)) {
            return false;
        } else if (angular.isUndefined(voucher.VoucherID)) {
            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.save = function () {
        $scope.voucher.Date = asDate($scope.voucher.Date);
        return $scope.voucher.$save({type: 'Purchase Return'}, function (u) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $location.path('/Return/' + u.VoucherID);
        }, function (data) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

    $scope.delete = function () {
        $scope.voucher.$delete(function () {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $location.path('/Return').replace();
        }, function (data) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

    $scope.post = function () {
        return $scope.voucher.$post(function () {
            $scope.toasts.push({Type: 'Success', Message: ''});
        }, function (data) {
            $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,
            size: 'lg',
            templateUrl: '/partial/purchase-return-modal.html',
            controller: PurchaseReturnModalController,
            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 () {
            $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, date: asDate($scope.voucher.Date)};
        return Batch.autocomplete(params).$promise;
    };
}];

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


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