const KTAppOptions = {
    "colors": {
        "state": {
            "brand": "#4d5cf2",
            "metal": "#c4c5d6",
            "light": "#ffffff",
            "accent": "#00c5dc",
            "primary": "#5867dd",
            "success": "#34bfa3",
            "info": "#36a3f7",
            "warning": "#ffb822",
            "danger": "#fd3995",
            "focus": "#9816f4"
        },
        "base": {
            "label": [
                "#c5cbe3",
                "#a1a8c3",
                "#3d4465",
                "#3e4466"],
            "shape": [
                "#f0f3ff",
                "#d9dffa",
                "#afb4d4",
                "#646c9a"]
        }
    }
};

function getPageLanguage() {
    return $('html').attr('lang');
}

function applyJournalCoverTheme() {
    let journalThemeBgs = $('.journal-theme-bg');
    if (journalThemeBgs.length > 0) {
        let src;

        jQuery.each(journalThemeBgs, function (i, el) {
            let $el = $(el);
            let journalCover = $el.data('journal-cover');

            if (typeof journalCover != 'undefined') {
                src = journalCover;
            }
        });

        if (typeof src != 'undefined') {
            $('body').append('<div style="display: none;"><canvas id="journal_cover_canvas_workspace" width="1" height="1"></canvas></div>');

            let c = document.getElementById('journal_cover_canvas_workspace');
            let ctx = c.getContext('2d');

            let image = new Image();
            image.src = src;
            image.onload = function () {
                ctx.drawImage(this, 0, 0);
                let mapPixel = ctx.getImageData(0, 0, 1, 1).data;

                $('.journal-theme-bg').css("background-color", "rgb(" + mapPixel[0] + "," + mapPixel[1] + "," + mapPixel[2] + ")");
            };
        }
    }
}

function initFileUploaders() {
    let $fileUploaders = $('.jb_fileupload');
    if ($fileUploaders.length > 0) {
        $fileUploaders.jbFileUpload();
    }
}

function initDpTooltips() {
    $('body').tooltip({
        selector: '[data-toggle="tooltip"]'
    });
}

function initSelect2() {
    $('.select2-element[data-ajax--url]').select2({
        ajax: {
            processResults: function (data) {
                return {
                    results: data
                };
            }
        }
    });

    $('.select2-element:not(.select2-element[data-ajax--url])').select2();

    $('.select2entity[data-ajax--url]').select2({
        ajax: {
            processResults: function (data) {
                return {
                    results: data
                };
            }
        }
    });
}

function initCollapsiblePortlets() {
    jQuery.each($('.portlet-collapsible'), function (i, el) {
        let $el = $(el);
        let id = $el.attr('id');

        if (typeof id == 'undefined') {
            id = 'collapsible_portlet_' + i;
            $el.attr('id', id);
        }

        const lang = getPageLanguage();
        const labels = {
            'en': {
                'collapse': 'Collapse',
                'expand': 'Expand'
            },
            'tr': {
                'collapse': 'Kapat',
                'expand': 'Genişlet'
            }
        };

        let tooltipsEnabled = true;
        let tooltipsOption = $el.attr('data-ktportlet-tooltips');

        if (typeof tooltipsOption != 'undefined' && tooltipsOption === 'false') {
            tooltipsEnabled = false;
        }

        new KTPortlet(id, {
            tooltips: tooltipsEnabled,
            tools: {
                toggle: {
                    collapse: labels[lang].collapse,
                    expand: labels[lang].expand,
                }
            }
        });
    });
}

function getDataTableLangData() {

    if (getPageLanguage() === 'tr') {
        return {
            "sDecimal": ",",
            "sEmptyTable": "Tabloda gösterilecek kayıt bulunmamaktadır.",
            "sInfo": "_TOTAL_ kayıttan _START_ - _END_ arasındaki kayıtlar gösteriliyor",
            "sInfoEmpty": "Kayıt yok",
            "sInfoFiltered": "(_MAX_ kayıt içerisinden bulunan)",
            "sInfoPostFix": "",
            "sInfoThousands": ".",
            "sLengthMenu": "Sayfada _MENU_ kayıt göster",
            "sLoadingRecords": "Yükleniyor...",
            "sProcessing": "İşleniyor...",
            "sSearch": "",
            "sZeroRecords": "Eşleşen kayıt bulunamadı",
            "oPaginate": {
                "sFirst": "İlk",
                "sLast": "Son",
                "sNext": "Sonraki",
                "sPrevious": "Önceki"
            },
            "oAria": {
                "sSortAscending": ": artan sütun sıralamasını aktifleştir",
                "sSortDescending": ": azalan sütun sıralamasını aktifleştir"
            },
            "select": {
                "rows": {
                    "_": "%d kayıt seçildi",
                    "0": "",
                    "1": "1 kayıt seçildi"
                }
            }
        };
    } else {
        return {
            "sSearch": ""
        };
    }
}

function initDataTables() {

    $.extend(true, $.fn.dataTable.defaults, {
        oLanguage: getDataTableLangData(),
        initComplete: function ($settings, $json) {

            var $input = $('.dataTables_filter input').unbind();
            $input.addClass('search-text');
            var $self = this.api();
            var $searchButton = $('<button class="search-button btn btn-sm btn-primary kt-margin-l-5">').text(Translator.trans('search')).click(function () {
                var $filterContainer = $(this).parent().closest('div.dataTables_filter');
                var $searchFilter = $filterContainer.find('select.search-filter').first();
                var $searchInput = $filterContainer.find('input').first();

                if ($searchFilter.length > 0) {
                    $self.context[0].ajax.data = { 'search[column]': $searchFilter.val() };
                }

                let $searchText = $searchInput.val().trim();
                if ($searchText.length > 0 && $searchText.length < 3) {
                    swal.fire(Translator.trans('datatables.search.text.length.info'), '', "info");
                } else {
                    $self.search($searchText).draw();
                }

            });

            let $selectFilter;
            if ($self.context[0].oInit.hasOwnProperty('individualFilters')) {
                let $select = '<select class="form-control form-control-sm search-filter kt-margin-b-5">';
                $.each($self.context[0].oInit.individualFilters, function ($column, $title) {
                    $select += '<option value="' + $column + '">' + Translator.trans($title) + "</option>";
                });
                $selectFilter = $select + '</select>';
            } else {
                $selectFilter = '';
            }

            $('.dataTables_filter').each(function () {
                if ($(this).find('button.search-button').length == 0) {
                    if ($selectFilter != '') {
                        $(this).prepend($selectFilter);
                    }
                    $(this).append($searchButton);
                }
            });
        }
    });

    $('body').on('keypress', 'input.search-text', function (e) {
        if (e.which === 13) {
            $(this).parent().closest('div.dataTables_filter').find('button.search-button').first().trigger('click');
        }
    });
}

function initUserNotificationCount() {
    if (isUserLoggedIn()) {

        $.ajax({
            url: Routing.generate('ojs_user_notification_unread_count'),
            type: "GET",
            success: function (total, textStatus, xhr) {
                if (xhr.status == 200 && total > 0) {
                    const $span = $("#user-notification-count > span");
                    $span.addClass('color-dergipark');
                    $span.html(' ' + total);

                    $('#mobile-notification-count-wrapper').removeClass('no-notification');
                    const $notificationBadge = $('#mobile-notification-badge');
                    $notificationBadge.html(total);
                }
            }
        });
    }
}

function initWysiwyg() {
    $('.wysihtml5').each(function () {
        let wysihtml5 = $(this);
        wysihtml5.summernote({
            height: 100,                 // set editor height

            minHeight: null,             // set minimum height of editor
            maxHeight: null,             // set maximum height of editor

            dialogsInBody: true,

            focus: false,                 // set focus to editable area after initializing summernote
            styleTags: [
                { title: 'Üst Başlık', tag: 'h4', className: 'h4', value: 'h4' },
                { title: 'Alt Başlık', tag: 'h5', className: 'h5', value: 'h5' },
                { title: 'Alıntı', tag: 'blockquote', className: 'blockquote', value: 'blockquote' },
                { title: 'Paragraf', tag: 'p', className: 'p', value: 'p' },
            ],
            imageAttributes: {
                icon: '<i class="note-icon-pencil"/>',
                figureClass: 'figureClass',
                figcaptionClass: 'captionClass',
                captionText: 'Caption Goes Here.',
                manageAspectRatio: true // true = Lock the Image Width/Height, Default to true
            },
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'clear']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture', 'hr']],
                ['view', ['fullscreen']]
            ],
            popover: {
                image: [
                    ['imagesize', ['imageSize100', 'imageSize50', 'imageSize25']],
                    ['float', ['floatLeft', 'floatRight', 'floatNone']],
                    ['remove', ['removeMedia']],
                    ['custom', ['imageAttributes']]
                ]
            },
            callbacks: {
                // callback for pasting text only (no formatting)
                onPaste: function (e) {
                    if (!wysihtml5.hasClass('html-enabled')) {
                        var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
                        e.preventDefault();
                        bufferText = bufferText.replace(/\r?\n/g, '<br>');
                        document.execCommand('insertHtml', false, bufferText);
                    }
                }
            }

        });

        $('form').on('submit', function () {
            if (wysihtml5.summernote('isEmpty')) {
                wysihtml5.val('');
            } else if (wysihtml5.val() === '<p><br></p>') {
                wysihtml5.val('');
            }
        });

    });

    // Fix z-index overlap for multiple WYSIWYG instances pn same page
    if ($('.note-editor .note-toolbar').length) {
        let z_index = 900;
        $(".note-editor .note-toolbar").each(function () {
            $(this).css({ 'z-index': z_index });
            z_index--;
        });
    }
}

function handleLinksWithConfirmation() {
    $('a[data-confirm]').each(function () {
        let $this = $(this);
        let confirmation_msg = $this.data('confirm');
        let link = $this.attr('href');

        if (typeof $this.data('token') !== undefined) {
            if (link.indexOf('?') > 0) {
                link = link + '&_token=' + $this.data('token');
            } else {
                link = link + '?_token=' + $this.data('token');
            }
        }

        let _method = 'GET';

        if (typeof $this.data('method') !== undefined) {
            _method = $this.data('method');
        }

        $this.attr('href', 'javascript: ;');

        $this.off('click').click(
            function () {
                swal.fire({
                    title: confirmation_msg,
                    type: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "Evet",
                    cancelButtonText: "Hayır",
                }).then(function (result) {
                    if (result.value) {
                        if (_method === 'GET') {
                            window.location.href = link;
                        } else {
                            $('body').append('<form action="' + link + '" id="dp_grid_delete_form" method="POST"><input name="_method" value="' + _method + '"></form>');
                            $('#dp_grid_delete_form').submit();
                        }
                    }
                });
            }
        );
    });
}

function removeNewPageIcon(){
    let newPageEl = $('#new_page');
    if(newPageEl.length > 0){
        let endDate = new Date(newPageEl.attr('data-end-date'));
        if((new Date).getTime() > endDate.getTime()){
            newPageEl.remove();
        }
    }
}

$(document).ready(function () {
    // Tooltip
    initDpTooltips();

    // Journal cover bg
    applyJournalCoverTheme();

    // Jquery File Upload
    initFileUploaders();

    // Collapsible Portlets
    initCollapsiblePortlets();
    // Select2
    initSelect2();

    // Trigger select2 element sortable function
    triggerSortable();

    $.fn.select2.defaults.set("theme", "bootstrap");

    // Revise datatable filter property for all
    initDataTables();

    // Set user unread notification count
    initUserNotificationCount();

    // Init WYSIWYG Editors
    initWysiwyg();

    // Handle links to be confirmed
    handleLinksWithConfirmation();

    // Remove new page icon if end date pass
    removeNewPageIcon();
});
