'use strict';

var LedgerController = ['$scope', '$routeParams', '$location', 'asDateFilter', 'ledger', 'Ledger', 'Account', function ($scope, $routeParams, $location, asDate, ledger, Ledger, Account) {
    $scope.info = ledger;
    $scope.hidden = [];
    $scope.show = function () {
        var id = $scope.info.Ledger.LedgerID,
            startDate = asDate($scope.info.StartDate),
            finishDate = asDate($scope.info.FinishDate);
        if (id === $routeParams.id && startDate === $routeParams.StartDate && finishDate === $routeParams.FinishDate) {
            Ledger.get({id: id, StartDate: startDate, FinishDate: finishDate}, function (data) {
                $scope.doFilter.cache = {};
                $scope.info = data;
            });
        } else {
            $location.path('/Ledger/' + id).search('StartDate', startDate).search('FinishDate', finishDate);
        }
    };

    $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.$watch('hidden', function () {
        var filtered = $scope.doFilter($scope.hidden, $scope.info.Body);
        $scope.ledger = filtered.Body;
        $scope.footer = filtered.Footer;
    }, true);

    $scope.$watch('info', function () {
        var filtered = $scope.doFilter($scope.hidden, $scope.info.Body);
        $scope.ledger = filtered.Body;
        $scope.footer = filtered.Footer;
    }, true);

    $scope.doFilter = _.memoize(function (hidden, input) {
        var data = angular.copy(input),
            debit = 0, credit = 0, running = 0;

        if (hidden.length !== 0) {
            data = _.filter(data, function (item) {
                return !_.any(hidden, function (hi) {
                    return item.ID === hi;
                });
            });
        }

        _.forEach(data, function (item) {
            if (item.Type !== 'Opening Balance') {
                debit += item.Debit;
                credit += item.Credit;
                if (item.Posted) {
                    running += item.Debit - item.Credit;
                }
            } else {
                running += item.Debit - item.Credit;
            }
            item.Running = running;
        });
        return {
            Body: data,
            Footer: {
                Debit: debit,
                Credit: credit,
                Running: running
            }
        };
    }, function (hidden) {
        return hidden.sort().join(' ');
    });

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

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

LedgerController.resolve = {
    ledger: ['$route', 'Ledger', function ($route, Ledger) {
        var id = $route.current.params.id,
            startDate = $route.current.params.StartDate,
            finishDate = $route.current.params.FinishDate;

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


