'use strict';

var ProductListCtrl = ['$scope', '$location', '$routeParams', 'Tokenizer', 'products', function ($scope, $location, $routeParams, Tokenizer, products) {
    $scope.search = $routeParams.q || '';
    $scope.showExtended = false;
    $scope.info = products;

    $scope.$watch('search', function (value) {
        $scope.filterProducts(value);
    }, true);

    $scope.$on('$destroy', function () {
        Tokenizer.doFilter.cache = {};
    });

    $scope.searchInfo = {
        comparator: {
            'n': {'Col': 'Name', 'Comparator': 'text'},
            'a': {'Col': 'IsActive', 'Comparator': 'boolean'},
            'u': {'Col': 'Units', 'Comparator': 'text'},
            't': {'Col': 'ProductGroup', 'Comparator': 'text'},
            'y': {'Col': 'ProductYield', 'Comparator': 'numeric'}
        },
        def: 'n',
        sorter: {
            'c': 'Code',
            'n': 'Name',
            'u': 'Units',
            'p': 'Price',
            't': 'ProductGroup',
            'a': 'IsActive',
            'y': 'ProductYield',
            'f': 'Fraction',
            'fu': 'FractionUnits'
        },
        flags: {
            'e': 'boolean'
        }
    };
    $scope.filterProducts = _.debounce(function (q) {
        if (q !== $scope._search) {
            $scope._search = q;
            if (angular.isUndefined(q) || q === '') {
                $location.path('/Products').search('q', null).replace();
            } else {
                $location.path('/Products').search({'q': q}).replace();
            }
            $scope.$apply(function () {
                var matches = Tokenizer.parseFilterString(q, $scope.searchInfo);
                $scope.showExtended = 'e' in matches.f;
                $scope.products = Tokenizer.doFilter(q, $scope.info, matches);

            });
        }
    }, 350);

    $scope.selected = -1;
    $scope.setSelected = function (index) {
        $scope.selected = Math.min(Math.max(0, index), $scope.products.length - 1);
    };
    $scope.shortcuts = {
        'up': function (e) {
            if ($scope.selected > 0) {
                $scope.$apply(function () {
                    $scope.selected = Math.min(Math.max(0, $scope.selected - 1), $scope.products.length - 1);
                });
                $("#" + $scope.selected).scrollintoview();
                e.preventDefault();
            }
        },
        'down': function (e) {
            if ($scope.selected < $scope.products.length - 1) {
                $scope.$apply(function () {
                    $scope.selected = Math.min(Math.max(0, $scope.selected + 1), $scope.products.length - 1);
                });
                $("#" + $scope.selected).scrollintoview();
                e.preventDefault();
            }
        }
    };
}];

ProductListCtrl.resolve = {
    products: ['Product', function (Product) {
        return Product.query({}).$promise;
    }]
};

var ProductCtrl = ['$scope', '$location', '$window', '$modal', 'product', 'productGroups', function ($scope, $location, $window, $modal, product, productGroups) {
    $scope.product = product;
    $scope.productGroups = productGroups;

    $scope.save = function () {
        $scope.product.$save(function (u) {
            $scope.toasts.push({Type: 'Success', Message: u.Code});
            $window.history.back();
        }, function (data) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

    $scope.delete = function () {
        $scope.product.$delete(function () {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $window.history.back();
        }, function (data) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

    $scope.confirm = function () {
        var modalInstance = $modal.open({
            backdrop: true,
            templateUrl: '/template/modal/confirm.html',
            controller: ['$scope', '$modalInstance', function ($scope, $modalInstance) {
                $scope.title = "Delete Product";
                $scope.body = "Are you sure? This cannot be undone.";
                $scope.isDelete = true;
                $scope.ok = function () {
                    $modalInstance.close();
                };
                $scope.cancel = function () {
                    $modalInstance.dismiss('cancel');
                };
            }]
        });
        modalInstance.result.then(function () {
            $scope.delete();
        });
    };

    $('#txtName').focus();
}];

ProductCtrl.resolve = {
    product: ['$route', 'Product', function ($route, Product) {
        var id = $route.current.params.id;

        return Product.get({id: id}).$promise;
    }],
    productGroups: ['ProductGroup', function (ProductGroup) {
        return ProductGroup.query({}).$promise;
    }]
};
