// Copyright Darko Gjorgjijoski <info@codeverve.com>
// 2020. All Rights Reserved.
// This file is licensed under the GPLv2 License.
// License text available at https://opensource.org/licenses/gpl-2.0.php

(function () {

    'use strict';

    /**
     * Create shortcode
     * @param data
     * @returns {string}
     */
    var create_shortcode = function (data) {
        var output = window.Vimeify_MCE_Config.markup;
        output = output.replace('{id}', data.uri);
        output = output.replace('{url}', 'https://vimeo.com/' + data.uri);
        return output;
    };

    /**
     * Insert in the current editor
     * @param data
     */
    var insert_in_editor = function (data) {
        if (!window.hasOwnProperty('currentEditor')) {
            return;
        }
        window.currentEditor.insertContent(create_shortcode(data));
    };

    // TinyMCE plugin
    if (typeof tinymce !== 'undefined') {
        tinymce.PluginManager.add('vimeify_vimeo_button', function (editor, url) {
            var tmpEditor = editor;
            var params = {
                text: window.Vimeify_MCE_Config.phrases.tmce_title,
                classes: 'ed_button button button-small',
                tooltip: window.Vimeify_MCE_Config.phrases.tmce_tooltip,
                onclick: function () {
                    window.currentEditor = tmpEditor;

                    var isAdmin = document.body.classList.contains('wp-admin');
                    var uploadModal = new window.Vimeify.UploaderModal('tinymce', {
                        source: isAdmin ? 'Backend.Editor.Classic' : 'Frontend.Editor.Classic'
                    });
                    uploadModal.open();
                }
            };

            if (window.Vimeify_MCE_Config.icon) {
                params.image = window.Vimeify_MCE_Config.icon_url;
            }

            editor.addButton('vimeify_vimeo_button', params);
        });
    }

    // Handle insert event
    window.addEventListener('vimeify.events.insert', function (e) {
        if (e.detail && e.detail.context === 'tinymce') {
            insert_in_editor(e.detail);
        }
    });

    // Handle upload event
    window.addEventListener('vimeify.events.upload', function (e) {
        if (e.detail && e.detail.context === 'tinymce') {
            insert_in_editor(e.detail);
        }
    });

})();
