(function ($) {

angular.module('dashnex')

    .controller('ImportContentController', ['$scope', '$http', function ($scope, $http) {

        $scope.request = {};
        $scope.results = [];

        $scope.categories = [];
        $scope.pages = [];
        $scope.posts = [];

        $scope.categoryKeywords = [];
        $scope.keywordsWithoutCategory = [];
        $scope.keywordsWithoutPage = [];
        $scope.keywordsWithoutPost = [];

        $scope.bulkCategories = [];
        $scope.bulkPages = [];
        $scope.bulkPosts = [];

        /**
         * Performs Assign action on WP category
         */
        $scope.assignCategory = function () {

            if (!$scope.request.category || !$scope.request.categoryKeyword) {
                return;
            }

            $scope.request.action = 'dashnex-import-content-category-assign';

            $http.post(ajaxurl, $scope.request)
                .success(function (response) {
                    $scope.processResponse(response);
                });
        };

        /**
         * Performs Create action on WP category
         */
        $scope.createCategory = function() {

            if (!$scope.request.category) {
                return;
            }

            $scope.request.action = 'dashnex-import-content-category-create';

            $http.post(ajaxurl, $scope.request)
                .success(function(response) {
                    $scope.processResponse(response);
                });
        };

        /**
         * Performs Create action on bulkCategories
         */
        $scope.bulkCreateCategories = function() {

            if (!$scope.bulkCategories) {
                return;
            }

            $scope.request.action = 'dashnex-import-content-category-bulk-create';
            $scope.request.categories = $scope.bulkCategories;

            $http.post(ajaxurl, $scope.request )
                .success(function(response) {
                    $scope.processResponse(response);
                });
        };

        /**
         * Performs assign Action on WP page
         */
        $scope.assignPage = function() {

            if (!$scope.request.page || !$scope.request.categoryKeyword) {
                return;
            }

            $scope.request.action = 'dashnex-import-content-page-assign';

            $http.post(ajaxurl, $scope.request)
                .success(function(response) {
                    $scope.processResponse(response);
                });

        };

        /**
         * Performs create Action on WP page
         */
        $scope.createPage = function() {

            if (!$scope.request.page) {
                return;
            }

            $scope.request.action = 'dashnex-import-content-page-create';

            $http.post(ajaxurl, $scope.request)
                .success(function(response) {
                    $scope.processResponse(response);
                });

        };

        /**
         * Performs bulk create Action on WP pages
         */
        $scope.bulkCreatePage = function() {

            if (!$scope.bulkPages) {
                return;
            }

            $scope.request.action = 'dashnex-import-content-page-bulk-create';
            $scope.request.pages = $scope.bulkPages;

            $http.post(ajaxurl, $scope.request)
                .success(function(response) {
                    $scope.processResponse(response);
                });
        };

        /**
         * Performs assign Action on WP post
         */
        $scope.assignPost = function() {

            if (!$scope.request.post || !$scope.request.contentKeyword) {
                return;
            }

            $scope.request.action = 'dashnex-import-content-post-assign';

            $http.post(ajaxurl, $scope.request)
                .success(function(response) {
                    $scope.processResponse(response);
                });

        };

        /**
         * Performs create Action on WP post
         */
        $scope.createPost = function() {

            if (!$scope.request.post || !$scope.request.parent) {
                return;
            }

            $scope.request.action = 'dashnex-import-content-post-create';

            $http.post(ajaxurl, $scope.request)
                .success(function(response) {
                    $scope.processResponse(response);
                });

        };

        /**
         * Performs bulk create Action on WP posts
         */
        $scope.bulkCreatePost = function() {

            if (!$scope.bulkPosts) {
                return;
            }

            $scope.request.action = 'dashnex-import-content-post-bulk-create';
            $scope.request.posts = $scope.bulkPosts;

            $http.post(ajaxurl, $scope.request)
                .success(function(response) {
                    $scope.processResponse(response);
                });
        };

        /**
         * Clears bulks and request object
         */
        $scope.clearData = function() {
            $scope.request = {};
            $scope.bulkPages = [];
            $scope.bulkPosts = [];
            $scope.bulkCategories = [];
        };

        /**
         * Adds value to request object under specified key.
         *
         * @param key
         * @param value
         */
        $scope.addToRequest = function(key, value) {
            $scope.request[key] = value;
        };

        /**
         * Adds all objects to bulk, or removes all from bulk
         *
         * @param bulkName
         * @param objects
         */
        $scope.toggleBulkAll = function(bulkName, objects) {
            var allInBulk = $scope[bulkName].length == objects.length;
            $scope[bulkName] = [];

            if (!allInBulk) {
                objects.forEach(function(obj){
                    $scope[bulkName].push(obj);
                });
            }
        };

        /**
         * Toggles selected object in bulk
         *
         * @param bulkName
         * @param object
         */
        $scope.toggleBulkObject = function(bulkName, object) {
            var index = $scope[bulkName].indexOf(object);

            if (index > -1) {
                $scope[bulkName].splice(index, 1);
            } else {
                $scope[bulkName].push(object);
            }
        };

        /**
         * Get selected in bulk objects names in one string
         *
         * @param bulkName
         * @param property
         * @returns {string}
         */
        $scope.getBulkObjectsNames = function(bulkName, property) {
            var names = [];

            $scope[bulkName].forEach(function(obj){
                names.push(obj[property]);
            });

            return names.join(', ');
        };

        /**
         * Adds/removes category to/from bulkCategories
         *
         * @param category
         */
        $scope.toggleBulkCategory = function(category) {

            var categoryIndex = $scope.bulkCategories.indexOf(category);

            if (categoryIndex > -1) {
                $scope.bulkCategories.splice(categoryIndex, 1);
                $scope.disableChildrenCategories(category);
            } else {
                if (!category.disabled) {
                    $scope.bulkCategories.unshift(category);
                }
                $scope.enableParentCategories(category);
            }
        };

        /**
         * Disables child categories, when theirs parents and grand*parents were unchecked
         *
         * @param category
         */
        $scope.disableChildrenCategories = function(category) {
            $.each(category.children, function(key, childCategory){

                var categoryIndex = $scope.bulkCategories.indexOf(childCategory);

                if (categoryIndex > -1) {
                    $scope.bulkCategories.splice(categoryIndex, 1);
                }

                $scope.disableChildrenCategories(childCategory);
            })
        };

        /**
         * Add parent categories for bulk action
         *
         * @param category
         */
        $scope.enableParentCategories = function(category) {

            var parent = $scope.parentCategorySearchRecursive(category, $scope.categories);

            category.parent = parent.id;

            while (parent) {
                var categoryIndex = $scope.bulkCategories.indexOf(parent);

                // removing parent element from it's position to add it to the beginning later
                if (categoryIndex > -1) {
                    $scope.bulkCategories.splice(categoryIndex, 1);
                }

                category = parent;
                parent = $scope.parentCategorySearchRecursive(category, $scope.categories);

                if (parent) {
                    category.parent = parent.id;
                }

                if (!category.disabled) {
                    $scope.bulkCategories.unshift(category);
                }
            }
        };

        /**
         * Searches for element in searchCategories, which contains childCategory
         *
         * @param childCategory
         * @param searchCategories
         * @returns {boolean}
         */
        $scope.parentCategorySearchRecursive = function(childCategory, searchCategories) {
            var result = false;

            for (var i in searchCategories) {
                var category = searchCategories[i];

                if (category == childCategory) {
                    return false;
                }

                if (category.children.indexOf(childCategory) > -1) {
                    return category;
                } else {
                    result = $scope.parentCategorySearchRecursive(childCategory, category.children);

                    if (result) {
                        return result;
                    }
                }
            }

            return result;
        };

        /**
         * Add all categories to bulkCategories to perform bulk action
         *
         * @param event
         */
        $scope.bulkAllCategories = function(event) {

            var isSetToChecked = event.target.checked;

            if (isSetToChecked) {
                $scope.bulkCategories = [];

                $.each($scope.categories, function(key, category){
                    if (!category.disabled) {
                        $scope.bulkCategories.push(category);
                    }
                    $scope.bulkChildCategories(category);
                })
            } else {
                $scope.bulkCategories = [];
            }
        };

        /**
         * Add category child categories to bulkCategories
         *
         * @param parentCategory
         */
        $scope.bulkChildCategories = function(parentCategory) {
            $.each(parentCategory.children, function(key,category) {
                category.parent = parentCategory.id;
                if (!category.disabled) {
                    $scope.bulkCategories.push(category);
                }
                $scope.bulkChildCategories(category);
            })
        };

        /**
         * Updates all data on the page to keep it fresh after actions on backend
         *
         * @param response
         */
        $scope.processResponse = function(response) {
            $scope.results = response.results;

            if (response.categories) {
                $scope.categories = response.categories;
            }
            if (response.pages) {
                $scope.pages = response.pages;
            }
            if (response.posts) {
                $scope.posts = response.posts;
            }
            if (response.categoryKeywords) {
                $scope.categoryKeywords = response.categoryKeywords;
            }
            if (response.keywordsWithoutCategory) {
                $scope.keywordsWithoutCategory = response.keywordsWithoutCategory;
            }
            if (response.keywordsWithoutPage) {
                $scope.keywordsWithoutPage = response.keywordsWithoutPage;
            }
            if (response.keywordsWithoutPost) {
                $scope.keywordsWithoutPost = response.keywordsWithoutPost;
            }

            $scope.clearData();
        };

    }])
})(jQuery);
