'use strict';

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

    $scope.voucher = voucher;
    $scope.ledgers = ledgers;
    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)) {
            $scope.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;
        $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, oldValue) {
        var amount = _.chain(journals)
            .where({'Debit': 1})
            .reduce(function (sum, item) {
                return item.Amount + sum;
            }, 0).value();

        var j = _.find(journals, {'Debit': -1});
        j.Amount = amount;
        if (_.find(oldValue, {'Debit': -1}).Ledger.LedgerID !== j.Ledger.LedgerID) {
            $location.search({a: j.Ledger.LedgerID}).replace();
        }
    }, true);

    $scope.preventAlteration = function (voucher) {
        if (angular.isUndefined($scope.perms)) {
            return false;
        } else if (angular.isUndefined(voucher.VoucherID)) {
            return !$scope.perms['Payment'];
        } 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: 'Payment'}, function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $location.path('/Payment/' + 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('/Payment').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/payment-modal.html',
            controller: PaymentModalController,
            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;
    };
}];

PaymentController.resolve = {
    voucher: ['$route', 'Voucher', function ($route, Voucher) {
        var id = $route.current.params.id,
            account = $route.current.params.a;

        if (angular.isUndefined(id)) {
            var options = {type: 'Payment'};
            if (!angular.isUndefined(account)) {
                options.a = account;
            }
            return Voucher.get(options).$promise;
        } else {
            return Voucher.get({id: id}).$promise;
        }
    }],
    ledgers: ['Account', function (Account) {
        return Account.autocomplete({term: '', type: 1}).$promise;
    }]
};

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