'use strict';

var ProductLedgerCtrl = ['$scope', '$routeParams', '$location', '$q', 'dateFilter', 'product_ledger', 'ProductLedger', 'Product', function ($scope, $routeParams, $location, $q, 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) {
        var deferred = $q.defer();
        Product.autocomplete({term: $viewValue, count: 20}, function (result) {
            deferred.resolve(result);
        });
        return deferred.promise;
    };

    $('#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;
    }]
}
