'use strict';

var RecipeListCtrl = ['$scope', 'recipes', function ($scope, recipes) {
    $scope.info = recipes;
    $scope.display = $scope.info;
    $scope.productTypeSelected = 'all';
    $scope.showLatest = 'latest';
    $scope.showSummary = 'no';

    $scope.$watch('productTypeSelected', function (value) {
        $scope.display = $scope.doFilter();
    }, true);
    $scope.$watch('showLatest', function (value) {
        $scope.display = $scope.doFilter();
    }, true);

    $scope.doFilter = function (q) {
        return _.filter($scope.info, function (item) {
            if ($scope.productTypeSelected === 'menu') {
                if (item.IsSemi) {
                    return false;
                }
            } else if ($scope.productTypeSelected === 'semi') {
                if (!item.IsSemi) {
                    return false;
                }
            }
            if ($scope.showLatest === 'latest' && !item.IsLatest) {
                return false;
            }
            return true;
        });
    };
}];

RecipeListCtrl.resolve = {
    recipes: ['Recipe', function (Recipe) {
        return Recipe.query({}).$promise;
    }]
};

var RecipeCtrl = ['$scope', '$location', '$window', '$modal', 'asDateFilter', 'Product', 'recipe', 'productGroups', function ($scope, $location, $window, $modal, asDate, Product, recipe, productGroups) {
    $scope.recipe = recipe;
    $scope.original = {};
    angular.copy($scope.recipe, $scope.original);
    $scope.productGroups = productGroups;
    $scope.costPrice = 0;
    function getOld(productID, recipeItems) {
        return _.find(recipeItems, function (recipe_item) {
            return recipe_item.Product.ProductID === productID;
        });
    }

    $scope.add = function () {
        if (!$scope.product || !$scope.product.ProductID || !$scope.quantity || Number(!$scope.quantity)) {
            return;
        }
        var oldItem = getOld($scope.product.ProductID, this.recipe.RecipeItems);
        if (angular.isUndefined(oldItem)) {
            var quantity = Number($scope.quantity);
            var price = Number($scope.product.Price);
            this.recipe.RecipeItems.push({
                Product: $scope.product,
                Quantity: quantity,
                Price: price
            });
        } else {
            $scope.toasts.push({Type: 'Danger', Message: 'Ingredient already in the list'});
        }
        delete $scope.quantity;
        delete $scope.product;
        $('#txtProduct').focus();
    };

    $scope.removeItem = function (item) {
        var index = this.recipe.RecipeItems.indexOf(item);
        this.recipe.RecipeItems.splice(index, 1);
    };

    $scope.$watch('recipe.RecipeItems', function (recipeItems) {
        if (!angular.isArray(recipeItems)) {
            return;
        }
        $scope.costPrice = recipeItems.reduce(function (sum, item) {
            var rate = item.Price / (item.Product.Fraction * item.Product.ProductYield);
            return sum + (item.Quantity * rate);
        }, 0);
    }, true);

    $scope.save = function () {
        $scope.recipe.Date = asDate($scope.recipe.Date);
        if (angular.isUndefined($scope.recipe.Date) || $scope.recipe.Date === '') {
            $scope.toasts.push({Type: 'Danger', Message: 'Please Choose a date'});
            return;
        }
        if ($scope.recipe.Date === $scope.original.Date) {
            var modalInstance = $modal.open({
                backdrop: true,
                templateUrl: '/template/modal/confirm.html',
                controller: ['$scope', '$modalInstance', function ($scope, $modalInstance) {
                    $scope.title = "Update Recipe?";
                    $scope.body = "Are you sure? This will overwrite the original recipe.";
                    $scope.isDelete = false;
                    $scope.ok = function () {
                        $modalInstance.close();
                    };
                    $scope.cancel = function () {
                        $modalInstance.dismiss('cancel');
                    };
                }]
            });
            modalInstance.result.then(function () {
                $scope.doSave();
            });
        } else {
            $scope.doSave();
        }
    };

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

    $scope.delete = function () {
        $scope.recipe.$delete(function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $window.history.back();
        }, 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 Recipe";
                $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();

    $scope.products = function ($viewValue) {
        return Product.autocomplete({term: $viewValue, count: 20, a: true, e: true, t: 'S'}).$promise;
    };

}];

RecipeCtrl.resolve = {
    recipe: ['$route', 'Recipe', function ($route, Recipe) {
        var id = $route.current.params.id;

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