system.controller("SeoAutolinkController", SeoAutolinkController);

function SeoAutolinkController($scope, $http, $rootScope, $interval, $window, Upload, $q) {
    this.__proto__ = new BaseController($scope, $http, $rootScope, Upload);

    const MODES = {
        'EDIT': 'edit',
        'CREATE': 'create'
    }

    $scope.categories = [
        {
            id: -1,
            title: 'All Product'
        },
        {
            id: -2,
            title: 'All Blog'
        },
        {
            id: -3,
            title: 'Landing Page'
        },
        {
            id: -4,
            title: 'Tag'
        },
        {
            id: -5,
            title: 'Homepage'
        }
    ];
    $scope.keywordLinks = [];
    $scope.productCategories = [];
    $scope.postCaregories = [];

    $scope.currentKeywordLink = {};
    $scope.state = {
        loading: false,
        mode: MODES.CREATE
    };
    $scope.filters = {};
    $scope.pagination = {
        current_page: 1,
        number_page: 1
    }
    $scope.locales = {};
    $scope.currentLocale = (CURRENT_LOCALE != '') ? CURRENT_LOCALE : 'us';

    async function init() {
        if (localesList) {
            for (var key in localesList) {
                if (localesList[key].text !== "Central") {
                    $scope.locales[key] = '';
                }
            }
        }

        $('#modalKeywordLink').on('shown.bs.modal', function () {
            $("#inputAnchortext").focus();
        });

        await fetchKeywords();
        await fetchCategory();

        mapKeywordNCategory();
    }

    $scope.openEditForm = function (keywordLink = null) {
        $scope.currentKeywordLink = {
            is_processing: 0,
            auto: 1,
            priority: 1,
            status: 'enable',
            category: { id: '-2' }  // all blog
        };
        if (keywordLink) {
            $scope.state.mode = MODES.EDIT;
            $scope.state.oldKeywordData = angular.copy(keywordLink)
            $scope.currentKeywordLink = angular.copy(keywordLink);
        } else {
            $scope.state.mode = MODES.CREATE;
        }

        $('#modalKeywordLink').modal({
            modal: true,
            persist: true,
            // position: [30, 0],
            autoPosition: true
        });

    }

    $scope.save = function () 
    {
        $scope.loaddingButton('#btnSaveKeywordLink', 'Saving . . .');
        $scope.state.loading = true;

        /* $scope.keywordLinks.forEach(keywordLink => {
            if ($scope.currentKeywordLink.id === keywordLink.id) {
                keywordLink.is_processing = 1;
                $scope.currentKeywordLink.is_processing = 1;
            }
        }); */

        // let oldData = buildSaveData($scope.state.oldKeywordData);
        let data = buildSaveData($scope.currentKeywordLink);
        // let hasChange = checkObjectChange(oldData, data);

        if (!data) {
            $scope.stopLoaddingButton('#btnSaveKeywordLink');
            $scope.state.loading = false;
            return;
        }

        storeKeywordLinks([data], function (response)
        {
            if (response.data.status === 'successful') {
                toastr.success('Saved');
                $scope.stopLoaddingButton('#btnSaveKeywordLink');

                refreshList().then(function() {
                    if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
                        $scope.$apply();
                    }
                });

                // restq_origin = '';

                /* for (let i = 0; i < response.data.result.length; i++) {
                    $http.post(restq_origin + prefixLocaleUrl + 'seo/autolink-v2/autolink', {
                        id: response.data.result[i].id
                    }).then(function () {
                        refreshList().then(function() {
                            if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
                                $scope.$apply();
                            }
                        });
                    });
                } */

                $('#modalKeywordLink').modal('hide');

            } else {
                toastr.error('Error saving keywordLink');
                console.log("Error", response)
            }

            $scope.state.loading = false;
        });
    }

    $scope.deleteKeywordLink = function (keywordLink) {
        const param = {
            title: 'Delete Item',
            customText: 'Confirm to delete this item!',
            confirmButtonText: 'Ok',
            cancelButtonText: 'No',
            arg: {id: keywordLink.id}
        };

        $scope.callConfirmModal(param, function (arg) {
            $http({
                method: 'delete',
                url: base_api_url + '/keyword_link/' + arg.id,
            }).then(function success(response) {
                if (response.data.status === 'successful') {
                    toastr.success('Deleted!');
                    refreshList();
                } else {
                    toastr.error('Error delete keywordLink!');
                }
            });
        });
    }

    $scope.removeAllFilters = function () {
        $scope.filters = {};
        refreshList();
    };

    $scope.range = function (min, max, step) {
        step = step || 1;
        const input = [];
        for (let i = min; i <= max; i += step) {
            input.push(i);
        }
        return input;
    };

    $scope.refreshList = refreshList;
    async function refreshList() {
        await fetchKeywords();
        mapKeywordNCategory();
    }

    $scope.importFile = function(files)
    {
        if (files && files[0]) {
            var locales = Object.keys($scope.locales);

            let file = files[0];
            if (['csv', 'xls', 'xlsx'].includes(file.name.split('.').pop())) {
                if (locales.length != 0) { // localizations
                    locales.forEach(function (locale) {
                        const url = $window.location.origin + `/${locale}/seo/autolink-keywords/import?ignore_localization=1`;
                        uploadFile(url, locale, file);
                    });
                } else {
                    const url = '/seo/autolink-keywords/import';
                    uploadFile(url, $scope.currentLocale, file);
                }
            } else {
                toastr.warning('Extention of file invalid!');
            }
        }
    }

    function uploadFile(url, locale, file) {
        $scope.state.loading = true;
        const formData = new FormData();
        formData.append("file", file);

        const request = new XMLHttpRequest();
        request.open("POST", url);
        request.onload = function (e) {

            const res = JSON.parse(this.responseText);
            if(res.status === 'successful') {
                if (res.result.length) {
                    toastr.success(`Successfully imported ${res.result.length} records for the ${locale.toUpperCase()} market.`);
                    refreshList().then(function() {
                        if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
                            $scope.$apply();
                        }
                    });
                }
            } else {
                toastr.error('Something went wrong please try again!');
            }

            $scope.$applyAsync(function () {
                $scope.state.loading = false;
            });

        };
        request.send(formData);
    }

    function buildSaveData(data) {
        let saveData = null;
        let validated = true;

        if (typeof data.keyword == 'undefined') {
            toastr.warning('Anchortext is invalid');
            validated = false;
        }

        let format = /[`!@#$%^&*()_+\=\[\]{};:"\\|,.<>\/?~]/;
        if (format.test(data.keyword)) {
            toastr.warning('Anchortext cannot contain special characters');
            validated = false;
        }

        if (typeof data.title == 'undefined' || !data.title) {
            toastr.warning('Title Anchortext is invalid');
            validated = false;
        }

        if (typeof data.auto == 'undefined' || data.auto <= 0) {
            toastr.warning('Number of replacement is invalid');
            validated = false;
        }
        if (typeof data.link == 'undefined' || !data.link) {
            toastr.warning('URL is invalid');
            validated = false;
        }
        if (typeof data.status == 'undefined' || !data.status) {
            toastr.warning('Status is invalid');
            validated = false;
        }
        if (typeof data.category == 'undefined') {
            toastr.warning('Category is invalid');
            validated = false;
        }

        if (validated) {
            saveData = {
                id: data.id,
                keyword: data.keyword,
                link: data.link,
                title: data.title,
                status: data.status,
                auto: data.auto,
                priority: data.priority,
                is_processing: data.is_processing,
                category_id: (typeof data.category != 'undefined') ? data.category.id : null
            };
        }

        return saveData;
    }

    function storeKeywordLinks(keywordLinks, callback) {
        $http({
            method: 'post',
            url: '/seo/autolink-keywords/store',
            data: { keywordLinks }
        }).then(function success(response) {
            if (response.data.status === 'successful') {
                callback(response);
            } else {
                toastr.error('Error store keywordLinks!');
            }
        });
    }

    function mapKeywordNCategory() {

        $scope.keywordLinks.forEach(_keywordLink => {
            let foundCategory = null;
            for (let i = 0; i < $scope.categories.length; i++) {
                const category = $scope.categories[i];
                let categoryId = (typeof _keywordLink.category != 'undefined') ? _keywordLink.category.id : _keywordLink.category_id;
                if (parseInt(category.id) === parseInt(categoryId)) {
                    foundCategory = angular.copy(category);
                    break;
                }
            }

            if (foundCategory) {
                foundCategory.id = foundCategory.id.toString();
                _keywordLink.category = foundCategory;
                _keywordLink.auto = parseInt(_keywordLink.auto);
            }

        });

        if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
            $scope.$apply();
        }
    }

    function fetchKeywords() {
        return new Promise(function (resolve) {
            let params = buildParamsFetchKeywords();
            let pageId = $scope.pagination.current_page - 1;
            $http.get(base_api_url + '/keyword_link?sorts=-id&filters=' + params + '&page_id=' + pageId).then(
                function success(response) {
                    if (response.data.status === 'successful') {
                        $scope.keywordLinks = response.data.result;

                        $scope.pagination.number_page = response.data.meta.page_count;
                        if ($scope.pagination.number_page < $scope.pagination.current_page) {
                            $scope.pagination.current_page = 1;
                        }

                        if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
                            $scope.$apply();
                        }

                        resolve();

                    } else {
                        resolve();
                    }
                },
                function error(response) {
                    resolve();
                    toastr.error(JSON.stringify(response));
                    console.log(response);
                }
            );
        });
    }

    function buildParamsFetchKeywords() {
        let filters = angular.copy($scope.filters);
        let params = [];

        if (filters.category_id) {
            params.push('category_id=' + filters.category_id);
        }
        if (filters.keyword) {
            params.push('keyword~' + filters.keyword);
        }
        if (filters.url) {
            params.push('link~' + filters.url);
        }
        if (filters.status) {
            params.push('status=' + filters.status);
        }

        return params.join(',');
    }

    function fetchCategory() {
        return new Promise(function (resolve) {
            Promise.all([$scope.getProductCategories(), $scope.getPostCategories()]).then(resp => {

                // product categories
                if (typeof resp[0] != 'undefined' && resp[0].data.status == 'successful') {
                    $scope.productCategories = standardizedCategories(resp[0].data.result);
                }

                // post categories
                if (typeof resp[1] != 'undefined' && resp[1].data.status == 'successful') {
                    $scope.postCategories = standardizedCategories(resp[1].data.result, 'POST');
                }

                $scope.categories = $scope.categories.concat($scope.postCategories, $scope.productCategories);

                resolve();

            }).catch()
        });
    }

    function standardizedCategories(categories, type = 'PRODUCT') {
        let returnValue = [];
        for (let i = 0; i < categories.length; i++) {
            const element = categories[i];
            let title = (typeof element.title != 'undefined' && element.title) ? element.title : element.name;
            returnValue.push({
                "id": element.id,
                "name": element.name,
                "title": title,
                "type": type
            });
        }
        return returnValue;
    }

    function checkObjectChange(newObj, oldObj) {
        return JSON.stringify(newObj) !== JSON.stringify(oldObj);
    }

    $scope.getProductCategories = function () {
        return $http.get(base_api_url + '/categories');
    }

    $scope.getPostCategories = function () {
        return $http.get(base_api_url + '/category?filters=type=POST&page_size=-1');
    }

    init();

}