'use strict';

function PurchaseReturnCtrl($scope, $location, voucher) {
    $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.addInventory = function () {
        var oldInventory = getOldInventory($scope.batch.Product.ProductID, this.voucher.Inventories),
            quantity = Number($scope.quantity);

        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:'Error', Message:data.data});
        });
    };

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

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

    $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;
            }
        }
    };
}

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

        var id = $route.current.params.id;

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

        if (typeof id === 'undefined') {
            Voucher.get({type:'Purchase Return'}, successCb);
        } else {
            Voucher.get({id:id}, successCb);
        }
        return deferred.promise;
    }
};