'use strict';

var ProductLedgerCtrl = ['$scope', '$routeParams', '$location', 'dateFilter', 'product_ledger', 'ProductLedger', 'Product', function ($scope, $routeParams, $location, dateFilter, product_ledger, ProductLedger, Product) {
    $scope.info = product_ledger;
    $scope.show = function () {
        var id = $scope.info.Product.ProductID;
        var start_date = angular.isDate($scope.info.StartDate) ? dateFilter($scope.info.StartDate, 'dd-MMM-yyyy') : $scope.info.StartDate;
        var finish_date = angular.isDate($scope.info.FinishDate) ? dateFilter($scope.info.FinishDate, 'dd-MMM-yyyy') : $scope.info.FinishDate;

        if (id === $routeParams.id && start_date === $routeParams.StartDate && finish_date === $routeParams.FinishDate) {
            ProductLedger.get({id: id, StartDate: start_date, FinishDate: finish_date}, function (data) {
                $scope.info = data;
            });
        } else {
            $location.path('/ProductLedger/' + $scope.info.Product.ProductID).search('StartDate', start_date).search('FinishDate', finish_date);
        }
    };
    $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 = {
    product_ledger: ['$route', 'ProductLedger', function ($route, ProductLedger) {
        var id = $route.current.params.id,
            start_date = $route.current.params.StartDate,
            finish_date = $route.current.params.FinishDate;

        if (typeof id === 'undefined') {
            return ProductLedger.get({}).$promise;
        } else {
            return ProductLedger.get({id: id, StartDate: start_date, FinishDate: finish_date}).$promise;
        }
    }]
};
