'use strict';

var JournalCtrl = ['$scope', '$location', 'voucher', function ($scope, $location, voucher) {
    $scope.voucher = voucher;
    $scope.name = '';
    $scope.debit = 1;
    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') {
            var amount = (oldJournal.Debit * oldJournal.Amount) + (parseInt($scope.debit) * Number($scope.amount));
            if (amount < 0) {
                oldJournal.Debit = -1;
                oldJournal.Amount = amount * -1;
            } else {
                oldJournal.Debit = 1;
                oldJournal.Amount = amount;
            }
        } else {
            this.voucher.Journals.push({Debit:$scope.debit, Amount:Number($scope.amount), Ledger:$scope.ledger});
        }
        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) {
        if (!angular.isArray(journals)) {
            return;
        }
        var amount = journals.reduce(function (previousValue, currentValue, index, array) {
            return previousValue + (currentValue.Amount * currentValue.Debit);
        }, 0);
        $scope.amount = Math.abs(amount);
    }, true);

    $scope.preventAlteration = function (voucher) {
        if (typeof $scope.perms === 'undefined') {
            return false;
        } else if (typeof voucher.VoucherID === 'undefined') {
            return !$scope.perms['Journal'];
        } 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:'Journal'}, function (u, putResponseHeaders) {
            $scope.toasts.push({Type:'Success', Message:''});
            $location.path('/Journal/' + 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('/Journal').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.toggleDebit = function () {
        $("#editDebit").button('toggle');
        $scope.edit.Debit = ($scope.edit.Debit === 1) ? -1 : 1;
    };
    $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;
            }
        }
    }
}]

JournalCtrl.resolve = {
    voucher:['$q', '$route', '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:'Journal'}, successCb);
        } else {
            Voucher.get({id:id}, successCb);
        }
        return deferred.promise;
    }]
};