'use strict';

var JournalCtrl = ['$scope', '$location', 'dateFilter', '$modal', 'voucher', 'Account', function ($scope, $location, dateFilter, $modal, voucher, Account) {
    $('#txtAccount').focus();

    $scope.voucher = voucher;
    $scope.debit = 1;
    function getOld(ledgerID, journals) {
        return _.find(journals, function (journal) {
            return journal.Ledger.LedgerID === ledgerID;
        });
    }

    $scope.add = function () {
        if (!$scope.account || !$scope.account.LedgerID || !$scope.amount || Number(!$scope.amount)) {
            return;
        }
        var oldJournal = getOld($scope.account.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.account});
        }
        delete $scope.account;
        delete $scope.amount;
        $('#txtAccount').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: 'Danger', Message: data.data});
        });
    };

    $scope.save = function () {
        if (angular.isDate($scope.voucher.Date)) {
            $scope.voucher.Date = dateFilter($scope.voucher.Date, 'dd-MMM-yyyy');
        }
        return $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: 'Danger', 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: 'Danger', Message: data.data});
        });
    };

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

    $scope.modal = function (journal) {
        $scope.selectedJournal = journal;
        var edit = {};
        angular.copy($scope.selectedJournal, edit);
        var modalInstance = $modal.open({
            backdrop: true,
            templateUrl: '/partial/journal-modal.html',
            controller: JournalModalCtrl,
            resolve: {edit: function () {
                return edit;
            }}
        });
        modalInstance.result.then(function (updated) {
                if (updated.Ledger.LedgerID !== $scope.selectedJournal.Ledger.LedgerID) {
                    var oldJournal = getOld(updated.Ledger.LedgerID, $scope.voucher.Journals);
                    if (typeof oldJournal !== 'undefined') {
                        delete $scope.selectedJournal;
                        return false;
                    }
                }
                angular.copy(updated, $scope.selectedJournal);
                delete $scope.selectedJournal;
            }, function () {
                delete $scope.selectedJournal;
            }

        )
        ;
    };

    $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}).$promise;
    };
}];

JournalCtrl.resolve = {
    voucher: ['$route', 'Voucher', function ($route, Voucher) {
        var id = $route.current.params.id;
        if (typeof id === 'undefined') {
            return Voucher.get({type: 'Journal'}).$promise;
        } else {
            return Voucher.get({id: id}).$promise;
        }
    }]
};

var JournalModalCtrl = ['$scope', '$modalInstance', 'edit', 'Account', function ($scope, $modalInstance, edit, Account) {
    $scope.toggleDebit = function () {
        $scope.edit.Debit = ($scope.edit.Debit === 1) ? -1 : 1;
    };

    $scope.edit = edit;
    $scope.ok = function () {
        $scope.edit.Amount = Number($scope.edit.Amount);
        $modalInstance.close($scope.edit);
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
    $scope.accounts = function ($viewValue) {
        return Account.autocomplete({term: $viewValue, count: 20}).$promise;
    };
}];
