/* --------------------------------------------------------------
 editor_values.js 2016-09-06
 Gambio GmbH
 http://www.gambio.de
 Copyright (c) 2016 Gambio GmbH
 Released under the GNU General Public License (Version 2)
 [http://www.gnu.org/licenses/gpl-2.0.html]
 --------------------------------------------------------------
 */

jse.libs.editor_values = jse.core.editor_values || {};

/**
 * ## Editor Values Library
 *
 * This library provides a common API for editor widget values manipulation.
 *
 * @module Admin/Libs/editor_values
 * @exports jse.libs.editor_values
 */
(function (exports) {

    'use strict';

    /**
     * Editor Get Value Methods
     *
     * @type {Object}
     */
    const getValue = {
        ckeditor($textarea) {
            const name = $textarea.attr('name');
            const instance = CKEDITOR.instances[name];
            return instance.getData();
        },

        codemirror($textarea) {
            const instance = $textarea.siblings('.CodeMirror')[0].CodeMirror;
            return instance.getDoc().getValue();
        }
    };

    /**
     * Editor Set Value Methods
     *
     * @type {Object}
     */
    const setValue = {
        ckeditor($textarea, value) {
            const name = $textarea.attr('name');
            const instance = CKEDITOR.instances[name];
            instance.setData(value);
        },

        codemirror($textarea, value) {
            const instance = $textarea.siblings('.CodeMirror')[0].CodeMirror;
            instance.getDoc().setValue(value);
        }
    };

    /**
     * Get Editor Value
     *
     * @param {jQuery} $textarea Textarea selector from which the value will be returned.
     *
     * @return {String} Returns the editor value.
     */
    exports.getValue = function ($textarea) {
        const type = $textarea.data('editorType');

        if (!getValue[type]) {
            throw new Error('Provided editor element does not have the supported types: ' + type);
        }

        return getValue[type]($textarea);
    };

    /**
     * Set Editor Value
     *
     * @param {jQuery} $textarea Textarea selector to which the value will be set.
     * @param {String} value The new value of the editor.
     */
    exports.setValue = function ($textarea, value) {
        const type = $textarea.data('editorType');

        if (!getValue[type]) {
            throw new Error('Provided editor element does not have the supported types: ' + type);
        }

        setValue[type]($textarea, value);
    };

})(jse.libs.editor_values);