'use strict';

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

    $scope.save = function () {
        $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:'Error', 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:'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.Product.ProductID) {
                    var oldInventory = getOldInventory(edit.Product.ProductID, $scope.voucher.Inventories);
                    if (typeof oldInventory !== 'undefined') {
                        return false;
                    }
                }
                edit.Quantity = Number(edit.Quantity);
                edit.Tax = (edit.Tax) ? Number(edit.Tax) : 0;
                edit.Discount = (edit.Discount) ? Number(edit.Discount) : 0;
                edit.Rate = Number(edit.Product.Price);
                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;
            }
        }
    };
}

PurchaseCtrl.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'}, successCb);
        } else {
            Voucher.get({id:id}, successCb);
        }
        return deferred.promise;
    }
};