// Copyright Upvimeo.com (https://upvimeo.com)
// 2025. All Rights Reserved.
// This file is licensed under the GPLv2 License.
// License text available at https://opensource.org/licenses/gpl-2.0.php

(function ($) {

    /**
     * Create shortcode
     * @param data
     * @returns {string}
     */
    var create_shortcode = function (data) {

        var output = UPVIMEO_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) {
        var content = create_shortcode(data);
        if (window.wp && window.wp.media && window.wp.media.editor) {
            window.wp.media.editor.insert(content);
        } else if (window.currentEditor) {
            window.currentEditor.insertContent(content);
        }
    }

    tinymce.PluginManager.add('UPVIMEO_vimeo_button', function (editor, url) {
        var tmpEditor = editor;
        var params = {
            text: UPVIMEO_MCE_Config.phrases.tmce_title,
            classes: 'ed_button button button-small',
            tooltip: UPVIMEO_MCE_Config.phrases.tmce_tooltip,
            onclick: function () {
                window.currentEditor = tmpEditor;
                var uploadModal = new WPVimeoVideos.UploaderModal('tinymce');
                uploadModal.open();
            }
        };
        if (UPVIMEO_MCE_Config.icon) {
            params.image = UPVIMEO_MCE_Config.icon_url;
        }
        editor.addButton('UPVIMEO_vimeo_button', params);
    });

    $(window).on('wpUPVIMEO.events.insert', function (e, data) {
        if (data.context === 'tinymce') {
            insert_in_editor(data);
        }
    })
    $(window).on('wpUPVIMEO.events.upload', function (e, data) {
        if (data.context === 'tinymce') {
            insert_in_editor(data);
        }
    })

    $(document).on('click', '.upvimeo-media-button', function (e) {
        e.preventDefault();
        var editorId = $(this).data('editor');
        if (editorId && window.tinymce) {
            window.currentEditor = window.tinymce.get(editorId);
        }
        if (!window.currentEditor) {
            window.currentEditor = window.wp && window.wp.media && window.wp.media.editor && window.wp.media.editor.activeEditor ? window.tinymce.get(window.wp.media.editor.activeEditor) : null;
        }
        if (!window.currentEditor && window.tinymce) {
            window.currentEditor = window.tinymce.activeEditor;
        }
        var uploadModal = new WPVimeoVideos.UploaderModal('tinymce');
        uploadModal.open();
    });

})(jQuery);
