'use strict';

var ProductListController = ['$scope', '$location', '$routeParams', 'Tokenizer', 'products', function ($scope, $location, $routeParams, Tokenizer, products) {
    $scope.search = $routeParams.q || '';
    $scope.showExtended = false;
    $scope.info = products;
    $scope.product_groups = _.reduce(products, function (acculumator, item) {
        if (!acculumator.includes(item.ProductGroup)){
            acculumator.push(item.ProductGroup);
        }
        return acculumator;
    },[]).sort();
    $scope.isPurchased = function (isPurchased) {
        if (arguments.length === 0) {
            return $scope._isPurchased;
        }
        $scope._isPurchased = isPurchased;
        var re = /(('[p]'|"[p]"|[p]+)\s*:\s*('[^']+'|"[^"]+"|[^\s]+))/gi,
            matches = $scope.search.match(re),
            st = isPurchased === 'null' ? '' : 'p:' + isPurchased,
            search = (matches === null) ? $scope.search.trim() + ' ' + st : $scope.search.replace(re, st);
        $scope.search = search.trim();
    };

    $scope.isSold = function (isSold) {
        if (arguments.length === 0) {
            return $scope._isSold;
        }
        $scope._isSold = isSold;
        var re = /(('[s]'|"[s]"|[s]+)\s*:\s*('[^']+'|"[^"]+"|[^\s]+))/gi,
            matches = $scope.search.match(re),
            st = isSold === 'null' ? '' : 's:' + isSold,
            search = (matches === null) ? $scope.search.trim() + ' ' + st : $scope.search.replace(re, st);
        $scope.search = search.trim();
    };

    $scope.productGroup = function (productGroup) {
        if (arguments.length === 0) {

            return $scope._productGroup;
        }
        $scope._productGroup = productGroup;
        var re = /(('[t]'|"[t]"|[t]+)\s*:\s*('[^']+'|"[^"]+"|[^\s]+))/gi,
            matches = $scope.search.match(re),
            st = 't:"' + productGroup + '"',
            search = (matches === null) ? $scope.search.trim() + ' ' + st : $scope.search.replace(re, st);
        $scope.search = search.trim();
    };

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

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

    $scope.searchInfo = {
        comparator: {
            'n': {'Col': 'Name', 'Comparator': 'text'},
            'u': {'Col': 'Units', 'Comparator': 'text'},
            'a': {'Col': 'IsActive', 'Comparator': 'boolean'},
            's': {'Col': 'IsSold', 'Comparator': 'boolean'},
            'p': {'Col': 'IsPurchased', 'Comparator': 'boolean'},
            '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();
            }
        }
    };
}];

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

var ProductController = ['$scope', '$location', '$window', '$mdDialog', 'product', 'productGroups', function ($scope, $location, $window, $mdDialog, 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 (ev) {
        $mdDialog.show({
            templateUrl: '/template/modal/confirm-material.html',
            parent: angular.element(document.body),
            targetEvent: ev,
            clickOutsideToClose: false,
            fullscreen: true,
            controller: ['$scope', '$mdDialog', function ($scope, $mdDialog) {
                $scope.title = "Delete Product";
                $scope.body = "Are you sure that you want to delete this product? This cannot be undone.";
                $scope.isDelete = true;
                $scope.ok = function () {
                    $mdDialog.hide();
                };
                $scope.cancel = function () {
                    $mdDialog.cancel();
                };
            }]
        }).then(function () {
            $scope.delete();
        });
    };
    $scope.foName = true;
}];

ProductController.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;
    }]
};
