'use strict';

var ReceiptCtrl = ['$scope', '$routeParams', '$location', '$q', 'dateFilter', '$modal', 'voucher', 'ledgers', 'Voucher', 'Account', function ($scope, $routeParams, $location, $q, dateFilter, $modal, voucher, ledgers, Voucher, Account) {
    $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.add = function () {
        if (!$scope.account || !$scope.account.LedgerID || !$scope.amount || Number(!$scope.amount)) {
            return;
        }
        var oldJournal = getOldJournal($scope.account.LedgerID, this.voucher.Journals);
        if (typeof oldJournal === 'undefined') {
            this.voucher.Journals.push({Debit: -1, Amount: Number($scope.amount), Ledger: $scope.account});
        } else {
            if (oldJournal.Debit === -1) {
                oldJournal.Amount = oldJournal.Amount + Number($scope.amount);
            } else {
                return;
            }
        }
        delete $scope.account;
        delete $scope.amount;
        $('#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: 'Danger', Message: data.data});
        });
    };

    $scope.save = function () {
        if (angular.isDate($scope.voucher.Date)) {
            $scope.voucher.Date = dateFilter($scope.voucher.Date, 'dd-MMM-yyyy');
        }
        $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: 'Danger', 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: 'Danger', 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: '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/receipt-modal.html',
            controller: ReceiptModalCtrl,
            resolve: {edit: function () {
                return edit;
            }}
        });
        modalInstance.result.then(function (updated) {
            if (updated.Ledger.LedgerID !== $scope.selectedJournal.Ledger.LedgerID) {
                var oldJournal = getOldJournal(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) {
        var deferred = $q.defer();
        Account.autocomplete({term: $viewValue, count: 20}, function (result) {
            deferred.resolve(result);
        });
        return deferred.promise;
    }

}]

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

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

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

var ReceiptModalCtrl = ['$scope', '$modalInstance', '$q', 'edit', 'Account', function ($scope, $modalInstance, $q, edit, Account) {
    $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) {
        var deferred = $q.defer();
        Account.autocomplete({term: $viewValue, count: 20}, function (result) {
            deferred.resolve(result);
        });
        return deferred.promise;
    }
}]
