'use strict';

var JournalController = ['$scope', '$location', 'asDateFilter', '$modal', 'uploadedImageResizer', 'voucher', 'Account', function ($scope, $location, asDate, $modal, uploadedImageResizer, voucher, Account) {
    $scope.foAccount = true;

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

    $scope.$on("fileSelected", function (event, args) {
        uploadedImageResizer(args, $scope.voucher.Files);
    });


    $scope.deleteFile = function (item) {
        var index = $scope.voucher.Files.indexOf(item);
        $scope.voucher.Files.splice(index, 1);
    };

    $scope.zoomImage = function (item) {
        $modal.open({
            templateUrl: '/template/modal/image.html',
            controller: ['$scope', '$modalInstance', function ($scope, $modalInstance) {
                $scope.imageUrl = item.Resized;
                $scope.size = null;
                $scope.cancel = function () {
                    $modalInstance.dismiss('cancel');
                };
            }]
        });
    };

    $scope.add = function () {
        if (!$scope.account || !$scope.account.LedgerID || !$scope.amount || Number(!$scope.amount)) {
            return;
        }
        var oldJournal = getOld($scope.account.LedgerID, $scope.voucher.Journals);
        if (!angular.isUndefined(oldJournal)) {
            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 {
            $scope.voucher.Journals.push({Debit: parseInt($scope.debit), Amount: Number($scope.amount), Ledger: $scope.account});
        }
        delete $scope.account;
        delete $scope.amount;
        $scope.foAccount = true;
    };

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

    $scope.$watch('voucher.Journals', function (journals) {
        if (!angular.isArray(journals)) {
            return;
        }
        var amount = journals.reduce(function (previousValue, currentValue) {
            return previousValue + (currentValue.Amount * currentValue.Debit);
        }, 0);
        $scope.amount = Math.abs(amount);
    }, true);

    $scope.preventAlteration = function (voucher) {
        if (angular.isUndefined($scope.perms)) {
            return false;
        } else if (angular.isUndefined(voucher.VoucherID)) {
            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.save = function () {
        $scope.voucher.Date = asDate($scope.voucher.Date);
        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,
            size: 'lg',
            templateUrl: '/partial/journal-modal.html',
            controller: JournalModalController,
            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 (!angular.isUndefined(oldJournal)) {
                        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;
    };
}];

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

var JournalModalController = ['$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;
    };
}];
