'use strict';

function ReceiptCtrl($scope, $routeParams, $location, voucher, ledgers, Voucher) {
    $scope.voucher = voucher;
    $scope.ledgers = ledgers;
    function getOldJournal(ledgerID, journals) {
        for (var i = 0, l = journals.length; i < l; i++) {
            if (journals[i].Ledger.LedgerID === ledgerID) {
                return journals[i];
            }
        }
    }

    $scope.addJournal = function () {
        var oldJournal = getOldJournal($scope.ledger.LedgerID, this.voucher.Journals);
        if (typeof oldJournal === 'undefined') {
            this.voucher.Journals.push({Debit:-1, Amount:Number($scope.amount), Ledger:$scope.ledger});
        } else {
            if (oldJournal.Debit === -1) {
                oldJournal.Amount = oldJournal.Amount + Number($scope.amount);
            } else {
                return;
            }
        }
        delete $scope.ledger;
        delete $scope.amount;
        $('#txtLedger').val('');
        $('#txtLedger').focus();
    };

    $scope.removeJournal = function (journal) {
        var index = this.voucher.Journals.indexOf(journal);
        this.voucher.Journals.splice(index, 1);
    };

    $scope.$watch('voucher.Journals', function (journals, oldValue) {
        var amount = 0;
        if (typeof journals !== 'undefined') {
            for (var i = 0, l = journals.length; i < l; i++) {
                if (journals[i].Debit === 1) {
                    var debitJournal = journals[i];
                } else {
                    amount += Number(journals[i].Amount);
                }
            }
            if (debitJournal.Amount !== amount) {
                debitJournal.Amount = amount;
            }
        }
    }, true);

    $scope.preventAlteration = function (voucher) {
        if (typeof $scope.perms === 'undefined') {
            return false;
        } else if (typeof voucher.VoucherID === 'undefined') {
            return !$scope.perms['Receipt'];
        } 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:'Receipt'}, function (u, putResponseHeaders) {
            $scope.toasts.push({Type:'Success', Message:''});
            $location.path('/Receipt/' + 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('/Receipt').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 (journal, update) {
        if (typeof update === 'undefined') {
            $scope.edit = {};
            angular.copy(journal, $scope.edit);
        } else {
            if (update === true && typeof $scope.edit !== 'undefined') {
                if (journal.Ledger.LedgerID !== $scope.edit.Ledger.LedgerID) {
                    var oldJournal = getOldJournal($scope.edit.Ledger.LedgerID, $scope.voucher.Journals);
                    if (typeof oldJournal !== 'undefined') {
                        return false;
                    }
                }
                $scope.edit.Amount = Number($scope.edit.Amount);
                angular.copy($scope.edit, journal);
                $scope.$apply();
                return true;
            } else if (update === false) {
                delete $scope.edit;
            }
        }
    }
}

ReceiptCtrl.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:'Receipt'}, successCb);
        } else {
            Voucher.get({id:id}, successCb);
        }
        return deferred.promise;
    },
    ledgers:function ($q, Account) {
        var deferred = $q.defer();

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

        Account.autocomplete({term:'', type:1}, successCb);
        return deferred.promise;
    }
};