'use strict';

var ProductLedgerCtrl = ['$scope', '$routeParams', '$location', 'asDateFilter', 'productLedger', 'ProductLedger', 'Product', function ($scope, $routeParams, $location, asDate, productLedger, ProductLedger, Product) {
    $scope.info = productLedger;
    $scope.show = function () {
        var id = $scope.info.Product.ProductID,
            startDate = asDate($scope.info.StartDate),
            finishDate = asDate($scope.info.FinishDate);
        if (id === $routeParams.id && startDate === $routeParams.StartDate && finishDate === $routeParams.FinishDate) {
            ProductLedger.get({id: id, StartDate: startDate, FinishDate: finishDate}, function (data) {
                $scope.info = data;
            });
        } else {
            $location.path('/ProductLedger/' + $scope.info.Product.ProductID).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));
    };

    $scope.products = function ($viewValue) {
        return Product.autocomplete({term: $viewValue, count: 20}).$promise;
    };

    $('#txtProduct').focus();
}];
ProductLedgerCtrl.resolve = {
    productLedger: ['$route', 'ProductLedger', function ($route, ProductLedger) {
        var id = $route.current.params.id,
            startDate = $route.current.params.StartDate,
            finishDate = $route.current.params.FinishDate;

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