<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

use Magento\Framework\App\TemplateTypesInterface;

// @codingStandardsIgnoreFile

/* @var $block \Magento\Newsletter\Block\Adminhtml\Template\Edit */
?>
<form action="<?php /* @escapeNotVerified */ echo $block->getSaveUrl() ?>" method="post" id="newsletter_template_edit_form">
    <?php echo $block->getBlockHtml('formkey')?>
    <div class="no-display">
        <input type="hidden" id="change_flag_element" name="_change_type_flag" value="" />
        <input type="hidden" id="save_as_flag" name="_save_as_flag" value="<?php /* @escapeNotVerified */ echo $block->getSaveAsFlag() ?>" />
    </div>
    <?php /* @escapeNotVerified */ echo $block->getForm() ?>
</form>
<form action="<?php /* @escapeNotVerified */ echo $block->getPreviewUrl() ?>" method="post" id="newsletter_template_preview_form" target="_blank">
    <?php echo $block->getBlockHtml('formkey')?>
    <div class="no-display">
        <input type="hidden" id="preview_type" name="type" value="<?php /* @escapeNotVerified */ echo $block->isTextType() ? 1 : 2 ?>" />
        <input type="hidden" id="preview_text" name="text" value="" />
        <input type="hidden" id="preview_styles" name="styles" value="" />
        <input type="hidden" id="preview_id" name="id" value="" />
    </div>
</form>
<script>
require([
    'jquery',
    'tinymce',
    'Magento_Ui/js/modal/prompt',
    'Magento_Ui/js/modal/confirm',
    'mage/mage',
    'prototype'
], function(jQuery, tinyMCE, prompt, confirm){

//<![CDATA[
    jQuery('#newsletter_template_edit_form').mage('form').mage('validation');
    jQuery('#newsletter_template_preview_form').mage('form').mage('validation');
    templateControl = {

        unconvertedText: '',
        typeChange: false,
        templateName: false,
        id: 'text',

        events: {
            'click [data-role=template-save]' : 'save',
            'click [data-role=template-save-as]': 'saveAs',
            'click [data-role=template-preview]' : 'preview',
            'click [data-role=template-unstrip]' : 'unStripTags',
            'click [data-role=template-strip]' : 'stripTags',
            'click [data-role=template-delete]': 'deleteTemplate'
        },

        init: function () {
            if ($('convert_button_back')) {
                $('convert_button_back').hide();
            }

            this.bindEvents();
        },

        bindEvents: function(){
            var events = this.events,
                eventName,
                selector,
                callback,
                key;

            for( key in events ){
                callback    = this[events[key]];
                key         = key.split(' ');

                eventName   = key[0];
                selector    = key.slice(1).join(' ');

                jQuery(selector).on(eventName, jQuery.proxy(callback, this) );
            }
        },

        stripTags: function () {
            var self = this;

            confirm({
                content: "<?php /* @escapeNotVerified */ echo __('Are you sure that you want to strip all tags?') ?>",
                actions: {
                    confirm: function(){
                        if(self.isEditor()) {
                            self.getEditor().turnOff();
                            self.getEditor().getToggleButton().hide();
                        }
                        self.unconvertedText = $(self.id).value;
                        $('convert_button').hide();
                        $('convert_button_back').show();
                        $(self.id).value =  $(self.id).value.stripScripts().stripTags();
                        $('field_template_styles').hide();
                        self.typeChange = true;
                    }
                }
            });

        },

        unStripTags: function () {
            $('convert_button').show();
            $('convert_button_back').hide();
            $(this.id).value =  this.unconvertedText;
            if(this.isEditor()) {
                this.getEditor().turnOn();
                this.getEditor().getToggleButton().show();
            }
            this.typeChange = false;
            $('field_template_styles').show();
            return false;
        },

        save: function() {
            if (this.typeChange) {
                $('change_flag_element').value = '1';
            }
            if(this.isEditor()) {
                tinyMCE.triggerSave();
            }
            // Temporary solution will be replaced after refactoring of newsletter functionality
            jQuery('#newsletter_template_edit_form').triggerHandler('save');
            return false;
        },

        saveAs: function() {
            var self = this;

            if (this.typeChange) {
                $('change_flag_element').value = '1';
            }

            if($F('code').blank() || $F('code')==templateControl.templateName) {

                prompt({
                    content: '<?php /* @escapeNotVerified */ echo __('Please enter a new template name.') ?>',
                    value: templateControl.templateName + '<?php /* @escapeNotVerified */ echo __(' Copy') ?>',
                    actions: {
                        confirm: function(value) {
                            $('code').value = value;
                            self._saveAs();

                            return false;
                        },
                        cancel: function(){
                            $('code').value = '';
                            // Temporary solution will be replaced after refactoring of newsletter functionality
                            jQuery('#newsletter_template_edit_form').triggerHandler('save');
                            self._saveAs();

                            return false;
                        }
                    }
                });
            }
        },

        _saveAs: function() {
            $('save_as_flag').value = '1';

            if(this.isEditor()) {
                tinyMCE.triggerSave();
            }
            // Temporary solution will be replaced after refactoring of newsletter functionality
            jQuery('#newsletter_template_edit_form').triggerHandler('save');
            return false;
        },

        preview: function() {
            if (this.typeChange) {
                $('preview_type').value = <?php /* @escapeNotVerified */ echo TemplateTypesInterface::TYPE_TEXT ?>;
            } else {
                $('preview_type').value = <?php /* @escapeNotVerified */ echo $block->getTemplateType() ?>;
            }
            if (this.isEditor() && tinyMCE.get(this.id)) {
                tinyMCE.triggerSave();
                $('preview_text').value = tinyMCE.get(this.id).getContent();
                tinyMCE.triggerSave();
            } else {
                $('preview_text').value = $(this.id).value;
            }
            if ($('template_styles') != undefined) {
                $('preview_styles').value = $('template_styles').value;
            }
            if ($('id') != undefined) {
                $('preview_id').value = $('id').value;
            }
            // Temporary solution will be replaced after refactoring of newsletter functionality
            jQuery('#newsletter_template_preview_form').triggerHandler('save');
            return false;
        },

        deleteTemplate: function() {
            confirm({
                content: "<?php /* @escapeNotVerified */ echo __('Are you sure you want to delete this template?') ?>",
                actions: {
                    confirm: function() {
                        window.location.href = '<?php /* @escapeNotVerified */ echo $block->getDeleteUrl() ?>';
                    }
                }
            });
        },

        isEditor: function() {
            return (typeof tinyMceEditors != 'undefined' && tinyMceEditors.get(this.id) != undefined)
        },

        getEditor: function() {
            return tinyMceEditors.get(this.id);
        }
    };

    templateControl.init();
    templateControl.templateName = "<?php /* @escapeNotVerified */ echo $block->getJsTemplateName() ?>";
//]]>

});
</script>
