'use strict';

var ProductLedgerCtrl = ['$scope', '$routeParams', '$location', 'product_ledger', function ($scope, $routeParams, $location, product_ledger, ProductLedger) {
    $scope.info = product_ledger;
    $scope.show = function () {
        var id = $scope.info.Product.ProductID;
        var start_date = $scope.info.StartDate;
        var finish_date = $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', $scope.info.StartDate).search('FinishDate', $scope.info.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));
    }
    $('#txtProduct').focus();
}]
ProductLedgerCtrl.resolve = {
    product_ledger:['$q', '$route', 'ProductLedger', function ($q, $route, ProductLedger) {
        var deferred = $q.defer();

        var id = $route.current.params.id;
        var start_date = $route.current.params.StartDate;
        var finish_date = $route.current.params.FinishDate;

        var successCb = function (result) {
            deferred.resolve(result);
        };

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