'use strict';

var ReconcileController = ['$scope', '$routeParams', '$location', 'asDateFilter', 'reconcile', 'Reconcile', 'Account', function ($scope, $routeParams, $location, asDate, reconcile, Reconcile, Account) {
    $scope.info = reconcile;
    $scope.show = function () {
        var id = $scope.info.Account.LedgerID,
            startDate = asDate($scope.info.StartDate),
            finishDate = asDate($scope.info.FinishDate);
        if (id === $routeParams.id && startDate === $routeParams.StartDate && finishDate === $routeParams.FinishDate) {
            Reconcile.get({id: id, StartDate: startDate, FinishDate: finishDate}, function (data) {
                $scope.info = data;
            });
        } else {
            $location.path('/Reconcile/' + id).search('StartDate', startDate).search('FinishDate', finishDate);
        }
    };

    $scope.save = function () {
        var i,
            len = $scope.body.length;
        $scope.info.Body = $scope.body;
        for (i = 0; i < len; i++) {
            $scope.info.Body[i].ReconcileDate = asDate($scope.info.Body[i].ReconcileDate);
        }
        $scope.info.$save({
            StartDate: $routeParams.StartDate,
            FinishDate: $routeParams.FinishDate
        }, function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $scope.info = u;
            $scope.doFilter();
        }, function (data, status) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

    $scope.downloadTable = function () {
        var table = $('#gvGrid'),
            html = table.clone().wrap('<div></div>').parent().html();
        html = html.replace(/á/g, '&aacute;');
        window.open('data:application/vnd.ms-excel;charset=UTF-8,' + encodeURIComponent(html));
    };

    if ($routeParams.id) {
        $scope.foGrid = true;
    } else {
        $scope.foLedger = true;
    }

    $scope.selected = -1;
    $scope.setSelected = function (index) {
        $scope.selected = index;
    };

    $scope.doFilter = function () {
        var data = angular.copy($scope.info.Body),
            debit = 0, credit = 0, running = 0;

        data = data.sort(function (a, b) {
            if (a.IsReconciled !== b.IsReconciled) {
                return b.IsReconciled - a.IsReconciled;
            }
            var aDate = moment(a.ReconcileDate, 'DD-MMM-YYYY');
            var bDate = moment(b.ReconcileDate, 'DD-MMM-YYYY');
            return aDate - bDate;
        });

        _.forEach(data, function (item) {
            if (item.Type !== 'Opening Balance') {
                debit += item.Debit;
                credit += item.Credit;
                if (item.IsReconciled) {
                    running += item.Debit - item.Credit;
                }
            } else {
                running += item.Debit - item.Credit;
            }
            item.Running = running;
        });
        $scope.body = data;
        $scope.footer = {
            Debit: debit,
            Credit: credit,
            Running: running
        }
    };

    $scope.doFilter();

    $scope.shortcuts = {
        'up': function (e) {
            if ($scope.selected > 0) {
                $scope.$apply(function () {
                    $scope.selected = Math.min(Math.max(0, $scope.selected - 1), $scope.body.length - 1);
                });
                $("#" + $scope.selected).scrollintoview();
                e.preventDefault();
            }
        },
        'down': function (e) {
            if ($scope.selected < $scope.info.Body.length - 1) {
                $scope.$apply(function () {
                    $scope.selected = Math.min(Math.max(0, $scope.selected + 1), $scope.body.length - 1);
                });
                $("#" + $scope.selected).scrollintoview();
                e.preventDefault();
            }
        },
        'enter': function (e) {
            var path = $scope.body[$scope.selected].Url.replace(/^(?:\/\/|[^\/]+)*/, "");
            $scope.$apply(function () {
                $location.path(path).search('StartDate', null).search('FinishDate', null);
            });
            e.preventDefault();
        }
    };

    $scope.accounts = function ($viewValue) {
        return Account.autocomplete({term: $viewValue, count: 20, r: true}).$promise;
    };
}];

ReconcileController.resolve = {
    reconcile: ['$route', 'Reconcile', function ($route, Reconcile) {
        var id = $route.current.params.id,
            startDate = $route.current.params.StartDate,
            finishDate = $route.current.params.FinishDate;

        if (angular.isUndefined(id)) {
            return Reconcile.get({}).$promise;
        } else {
            return Reconcile.get({id: id, StartDate: startDate, FinishDate: finishDate}).$promise;
        }
    }]
};
