'use strict';

var ProductListCtrl = ['$scope', '$location', '$routeParams', 'products', function ($scope, $location, $routeParams, products) {
    $scope.search = $routeParams.q || '';
    $scope.info = products;
    var re = /((([^ ]+):\s*('[^':]+'|"[^":]+"|[^ ]+))|[^ ]+[^: '"]*)/g;

    $scope.isTrue = function (value) {
        value = value.toLowerCase();
        return !_.any(['f', 'fa', 'fal', 'fals', 'false', 'n', 'no', '0'], function (item) {
            return item === value;
        });
    };

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

    $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 () {
                $scope.products = $scope.doFilter(q);
            });
        }
    }, 350);
    $scope.doFilter = _.memoize(function (q) {
        var matches = [], i, len;
        if (angular.isUndefined(q) || q === '') {
            return $scope.info;
        }
        var m = q.match(re);
        _.forEach(m, function (item) {
            item = item.toLowerCase();
            if (item.indexOf(':') === -1) {
                matches.push({'key': 'n', 'value': item});
            } else {
                var key = item.substr(0, item.indexOf(':')).toLowerCase();
                var value = item.substr(item.indexOf(':') + 1, item.length).trim().toLowerCase();
                if (value.indexOf("'") === 0 || value.indexOf('"') === 0) {
                    value = value.substring(1, value.length - 2);
                }
                if (key !== '' && value !== '' && _.any(['w', 'u', 'g'], function (item) {
                    return item === key;
                })) {
                    matches.push({'key': key, 'value': value});
                }
            }
        });
        return _.filter($scope.info, function (item) {
            len = matches.length;
            for (i = 0; i < len; i++) {
                var match = matches[i];
                if (match.key === 'n') {
                    if (item.Name.toLowerCase().indexOf(match.value) === -1) {
                        return false;
                    }
                } else if (match.key === 'w') {
                    if (item.Discontinued === $scope.isTrue(match.value)) {
                        return false;
                    }
                } else if (match.key === 'u') {
                    if (item.Units.toLowerCase().indexOf(match.value) === -1) {
                        return false;
                    }
                } else if (match.key === 'g') {
                    if (item.ProductGroup.toLowerCase().indexOf(match.value) === -1) {
                        return false;
                    }
                }
            }
            return true;
        });
    });
}];

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

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

    $scope.save = function () {
        $scope.product.$save(function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: u.Code});
            $location.path('/Products');
        }, function (data, status) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

    $scope.delete = function () {
        $scope.product.$delete(function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $location.path('/Products');
        }, function (data, status) {
            $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;
    }],
    product_groups: ['ProductGroup', function (ProductGroup) {
        return ProductGroup.query({}).$promise;
    }]
};
