system.controller("MetaDataController", MetaDataController);

function MetaDataController($rootScope, $scope, $http, Upload, $timeout, $window) {
    $scope.pageSize = 20;
    $scope.filter = {
        page_id: 0
    };
    $scope.items = [];
    $scope.metaData = {};
    $scope.mode = "create"; $scope.failMessage = null; $scope.frontendDomain = '';
    
    $scope.locales = {};
    $scope.currentLocale = (CURRENT_LOCALE != '') ? CURRENT_LOCALE : 'us';

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

        $scope.find();
    }


    $scope.baseController = this.__proto__ = new BaseController($scope, $http, $rootScope, $timeout);

    $scope.create = () => {
        $scope.metaData = {};
        $scope.titleModal = "New Meta data";
        $("#modalRedirect").modal();
        $timeout(function() {
            if (tinymce.get('content')) {
                tinymce.get('content').remove();
            }
            if (tinymce.get('content-footer')) {
                tinymce.get('content-footer').remove();
            }
            initTinymce("#content", 150, false, function () {
                tinymce.get('content').setContent('');
            });
            initTinymce("#content-footer", 150, false, function () {
                tinymce.get('content-footer').setContent('');
            });
        });
    };

    $scope.reset = function () {
        $scope.filter = {
            page_id: 0
        };
        $scope.find();
    }

    $scope.find = function () {
        $scope.isShowHideLoading(true);
        var data = $.param($scope.buildFilterData());
        if (data != '') data = '?' + data;
        $http.get('/seo/meta-data/find' + data).then(function mySuccess(response) {
            $scope.isShowHideLoading(false);
            if(response.data.status == "successful") {
                $scope.items = response.data.items;
                $scope.pagesCount = parseInt(response.data.pagesCount);
                if ($scope.filter.page_id > 0 && $scope.items.length == 0) {
                    $scope.filter.page_id = 0;
                    $scope.find();
                }
            } else {
                alert('Có lỗi xảy ra trong quá trình lấy dữ liệu. Vui lòng thử lại...');
            }
        }, function myError() {
            $scope.isShowHideLoading(false);
            alert('Có lỗi xảy ra trong quá trình lấy dữ liệu. Vui lòng thử lại...');
        });
    }

    $scope.save = function () {

        var data = $scope.buildData();
        if(!data) return;

        $scope.isShowHideLoading(true);
        let url = '/seo/meta-data/save';
        let method = 'post';
        if (data.id) {
            url += '/' + data.id;
            method = 'PATCH';
        }
        var request = $http({
            url: url,
            method: method,
            data: data
        });
        var mode = "create";
        request.then(function mySuccess(response) {
            $scope.isShowHideLoading(false);
            if (response.data.status == "successful") {
                if(!data.id) {
                    $scope.items.unshift(response.data.result);
                } else {
                    for(var i = 0, l = $scope.items.length; i < l; i++) {
                        if($scope.items[i].id == response.data.result.id) {
                            $scope.items[i] = response.data.result;
                            break;
                        }
                    }
                }
                $("#modalRedirect").modal("hide");
            } else {
                $scope.failMessage = response.data.message;
            }
        }, function myError() {
            $scope.isShowHideLoading(false);
            alert('Có lỗi xảy ra trong quá trình lưu dữ liệu. Vui lòng thử lại...');
        });
    }

    $scope.edit = function (item) {
        $scope.mode = "update";
        var tempCopy = angular.copy(item);
        $scope.metaData = {
            id: tempCopy.id,
            url: $scope.frontendDomain + tempCopy.url,
            metaTitle: tempCopy.meta_title,
            metaKeywords: tempCopy.meta_keywords,
            metaDescription: tempCopy.meta_description,
            content: tempCopy.content || '',
            content_footer: tempCopy.content_footer || '',
            heading: tempCopy.heading || '',
            isGenerateContentFooter: tempCopy.is_generate_content_footer || 0
        };
        if (tempCopy.canonical) {
            $scope.metaData.canonical = $scope.frontendDomain + tempCopy.canonical;
        }
        $scope.baseController.openDialogModal("#metaDataForm");
        $timeout(function() {
            if (tinymce.get('content')) {
                tinymce.get('content').remove();
            }
            if (tinymce.get('content-footer')) {
                tinymce.get('content-footer').remove();
            }
            var content = $scope.metaData.content || '';
            $scope.baseController.initTinymce("#content", 150, false, function () {
                tinymce.get('content').setContent(content);
            });
            var contentFooter = $scope.metaData.content_footer || '';
            $scope.baseController.initTinymce("#content-footer", 150, false, function () {
                tinymce.get('content-footer').setContent(contentFooter);
            });
        });
    }

    $scope.delete = function (item, index) {
        var check = confirm('Confirm URL deletion: ' + item.url + '!');
        if (check) {
            $scope.isShowHideLoading(true);
            $http.post('/seo/meta-data/delete', {id: item.id}).then(function mySuccess(response) {
                $scope.isShowHideLoading(false);
                if(response.data.status == "successful") {
                    $scope.items.splice(index, 1);
                } else {
                    alert("An error occurred!\n" + response.data.message);
                }
            }, function myError() {
                $scope.isShowHideLoading(false);
                alert('An error occurred during URL deletion. Please try again.');
            });
        }
    }

    $scope.buildData = function () {
        $scope.failMessage = null;

        var retVal = {};

        if ($scope.metaData.id && $scope.metaData.id != "") {
            retVal.id = $scope.metaData.id;
        }

        if (!$scope.metaData.url || $scope.metaData.url == "") {
            $scope.failMessage = "Please enter Url for this MetaData...";
            return false;
        } else {
            retVal.url = $scope.metaData.url;
        }

        if(!$scope.metaData.metaTitle || $scope.metaData.metaTitle == "") {
            $scope.failMessage = "Please enter Meta Tilte";
            return false;
        } else {
            retVal.metaTitle = $scope.metaData.metaTitle;
        }

        if(!$scope.metaData.metaKeywords || $scope.metaData.metaKeywords == "") {
            $scope.failMessage = "Please enter Meta Keywords.";
            return false;
        } else {
            retVal.metaKeywords = $scope.metaData.metaKeywords;
        }

        if(!$scope.metaData.metaDescription || $scope.metaData.metaDescription == "") {
            $scope.failMessage = "Please enter Meta Description.";
            return false;
        } else {
            retVal.metaDescription = $scope.metaData.metaDescription;
        }

        if($scope.metaData.heading && $scope.metaData.heading != "") {
            retVal.heading = $scope.metaData.heading;
        }

        if($scope.metaData.canonical && $scope.metaData.canonical != "") {
            retVal.canonical = $scope.metaData.canonical;
        }
        if($scope.metaData.isGenerateContentFooter && $scope.metaData.isGenerateContentFooter != "") {
            retVal.is_generate_content_footer = $scope.metaData.isGenerateContentFooter;
        }

        retVal.content = tinymce.get('content').getContent();
        retVal.content_footer = tinymce.get('content-footer').getContent();

        return retVal;
    }

    $scope.isValidLink = function (link) {
        var regex = /(^|\s)((https?:\/\/)[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi;
        return regex.test(link);
    }

    $scope.handleUpload = function (excelFile) {
        if (excelFile) {
            $scope.isShowHideLoading(true);
            var locales = Object.keys($scope.locales)
            if (locales.length != 0) { // localizations
                locales.forEach(function (locale) {
                    const url = $window.location.origin + `/${locale}/seo/meta-data/import?ignore_localization=1`;
                    uploadFile(url, excelFile, locale);
                });
            } else {
                const url = '/seo/meta-data/import';
                uploadFile(url, excelFile, $scope.currentLocale);
            }
        }
    }

    function uploadFile(url, excelFile, locale) {
        Upload.upload({
            url: url,
            data: { excelFile: excelFile }
        }).then( function (response) {
            if (response.data.status == "successful") {
                toastr.success(`Successfully imported ${response.data.affectedRow} records for the ${locale.toUpperCase()} market.`);
                $scope.find();
            } else {
                $scope.isShowHideLoading(false);
                $scope.failMessage = 'An error occurred during Import MetaData. Please try again..';
            }
        }, function (error) {
            $scope.isShowHideLoading(false);
            $scope.failMessage = 'An error occurred during Import MetaData. Please try again...';
        });
    }

    $scope.export = function () {
        var filterParam = angular.copy($scope.filter);
        delete filterParam.pageId;
        filterParam = $scope.buildFilterData();
        filterParam.export = 'excel';
        var data = $.param(filterParam);
        if (data != '') data = '?' + data;
        var url = '/seo/meta-data/find' + data;
        if (CURRENT_LOCALE) {
            url = '/' + CURRENT_LOCALE + url;
        }
        window.open(url, '_blank');
    }

    $scope.myFunct = function (keyEvent) {
        if (keyEvent.which === 13) $scope.find();
    };

    $scope.buildFilterData = function () {
        var retVal = {
            pageId: $scope.filter.page_id,
            pageSize: $scope.pageSize
        };
        if ($scope.filter.url && $scope.filter.url != '') {
            retVal.url = $scope.filter.url;
        }
        return retVal;
    }

    $scope.isShowHideLoading = function (val) {
        $scope.isShowLoading = val;
    };

    $scope.openModal = (metaData) => {
        var tempCopy = angular.copy(metaData);
        $scope.metaData = {
            id: tempCopy.id,
            url: tempCopy.url,
            metaTitle: tempCopy.meta_title,
            metaKeywords: tempCopy.meta_keywords,
            metaDescription: tempCopy.meta_description,
            content: tempCopy.content || '',
            content_footer: tempCopy.content_footer || '',
            heading: tempCopy.heading || '',
        };
        if (tempCopy.canonical) {
            $scope.metaData.canonical = $scope.frontendDomain + tempCopy.canonical;
        }
        $scope.titleModal = "Edit meta data";
        $("#modalRedirect").modal();
        $timeout(function() {
            if (tinymce.get('content')) {
                tinymce.get('content').remove();
            }
            if (tinymce.get('content-footer')) {
                tinymce.get('content-footer').remove();
            }
            var content = $scope.metaData.content || '';
            initTinymce("#content", 150, false, function () {
                tinymce.get('content').setContent(content);
            });
            var contentFooter = $scope.metaData.content_footer || '';
            initTinymce("#content-footer", 150, false, function () {
                tinymce.get('content-footer').setContent(contentFooter);
            });
        });
    };

    function initTinymce (selector, height, readonly, callBackFn) {
        height = height == null ? 250 : height;
        readonly = readonly == null ? 0 : readonly;
        var options = {
            selector: selector,
            plugins: [
                "advlist autolink lists link image charmap print preview anchor",
                "searchreplace visualblocks code fullscreen imageupload formatpainter",
                "insertdatetime media table contextmenu paste textcolor customfaq excelfaq"
            ],

            toolbar: "fontselect | fontsizeselect | styleselect | formatpainter bold italic underline | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | imageupload | customfaq | excelfaq",
            fontsize_formats: "8pt 9pt 10pt 11pt 12pt 13pt 14pt 15pt 16pt 17pt 18pt 20pt 24pt 36pt",
            width: '98.5%',
            extended_valid_elements : "script[src|async|defer|type|charset]",
            formatpainter_removeformat: [
                { selector: 'b,strong,em,i,font,u,strike,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins',
                    remove: 'all',
                    split: true,
                    expand: false,
                    block_expand: true,
                    deep: true
                },
                { selector: 'span',
                    attributes: ['style', 'class'],
                    remove: 'empty',
                    split: true,
                    expand: false,
                    deep: true
                },
                { selector: '*:not(tr,td,th,table)',
                    attributes: ['style', 'class'],
                    split: false,
                    expand: false,
                    deep: true
                }
            ],
            paste_retain_style_properties: "all",
            paste_strip_class_attributes: "none",
            height: height,
            readonly: readonly,
            relative_urls: false,
            remove_script_host: true,
            setup: function (editor) {
                editor.on('change', function () {
                    tinymce.triggerSave();
                    $scope.$apply(() => {
                        let field = selector.replace('#', '').replace('-', '_');
                        $scope.metaData[field] = tinymce.get(selector.replace('#', '')).getContent();
                    })
                });
                editor.on('init',callBackFn);
            },
            cache_suffix: "?v=1.1"
        };
        tinymce.init(options);
    };

    $scope.getTemplate = function () {
        window.open('/modules/seo/files/MetaData_Template.xlsx?v=2', '_blank').focus();
    }

    $scope.init();
}
