{% extends 'admin/change_form.html' %}

{% load static %}
{% load static grapesjs_tags %}

{% block extrahead %}{{ block.super }}
<script>
    var replaceTagsInit = [
        {% get_settings_value "REPLACE_INIT_IGNORE_TAGS" safe=True %},
        {% get_settings_value "REPLACE_INIT_HIDDEN_TAGS" safe=True %}
    ]
    var replaceTagsSave = [
        {% get_settings_value "REPLACE_SAVE_IGNORE_TAGS" safe=True %},
        {% get_settings_value "REPLACE_SAVE_HIDDEN_TAGS" safe=True %}
    ]

    function normalizeData(value, save) {
        /**
        * I add this tag because grapesjs works only with markup.
        * If in your resource only a django tags or jinja this will help you avoid mistakes
        */
        stringBegin = '<div temporary="">';
        stringEnd = '</div label>';

        if (save) {
            return value.replace(stringBegin, '').replace(stringEnd, '')
        }
        else {
            return stringBegin + value + stringEnd
        }
    }

    function replaceTag(value, replaceTagsArray) {
        for (var i=0; i<replaceTagsArray.length; i++) {
            for (var tag in replaceTagsArray[i]) {
                if (replaceTagsArray[i].hasOwnProperty(tag)) {
                    value = value.replace(new RegExp(tag, 'g'), replaceTagsArray[i][tag]);
                }
            }
        }
        return value;
    }

    function setFilesStatic(grapesjs, name) {
        if({% get_settings_value "GRAPESJS_SAVE_ASSETS_TO_FILE" %} && {{ original.id|yesno:"1,0" }}) {
            const id = "{{ original.id }}";
            const scriptTagName = 'script'
            const script = `<${scriptTagName} src="/media/grapesjs/${name}_${id}_js.js"></${scriptTagName}>`
            const linkHref = `/media/grapesjs/${name}_${id}_css.css`
            grapesjs.addComponents([script]);
            fetch(linkHref)
            .then(response => response.text())
            .then(response => grapesjs.addStyle(response))
            .catch(err => console.log(err))
        }
    }
</script>
{% endblock %}

{% block admin_change_form_document_ready %}{{ block.super }}
<script>
    function getCssGrapesjs(value, css) {
        regexStyle = /(<style grapesjs type=.+)((\s+)|(\S+)|(\r+)|(\n+))(.+)((\s+)|(\S+)|(\r+)|(\n+))(<\/style>)/g;
        return value.replace(regexStyle, "") + "<style grapesjs type=\"text/css\">" + css + "</style>";
    }

    function setHtmlInTheField() {
        all_id = document.getElementsByName("get-all-id");

        for (i=0; i < all_id.length; i++) {
            field = document.getElementById(all_id[i].textContent);

            htmlGrapesjs = replaceTag(
                this["editor_" + all_id[i].textContent].getHtml(),
                replaceTagsSave
            );
            const script_regex = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
            const style_regex = /<style\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/style>/gi;

            if({% get_settings_value "GRAPESJS_SAVE_ASSETS_TO_FILE" %}) {
                const fieldName = all_id[i].textContent;
                const css = this["editor_" + fieldName].getCss()
                const js = this["editor_" + fieldName].getJs()
                document.querySelector(`#${fieldName}_js`).value = js
                document.querySelector(`#${fieldName}_css`).value = css
                htmlGrapesjs = htmlGrapesjs.replace(script_regex, "")
                htmlGrapesjs = htmlGrapesjs.replace(style_regex, "")
                htmlGrapesjs = htmlGrapesjs.replace('<body>', "")
                htmlGrapesjs = htmlGrapesjs.replace('</body>', "")
                window.onbeforeunload = function() {
                    return true;
                };
            } else if ({% get_settings_value "GRAPESJS_SAVE_CSS" %}) {
                htmlGrapesjs = getCssGrapesjs(
                    htmlGrapesjs, this["editor_" + all_id[i].textContent].getCss()
                )
            }

            field.value = normalizeData(htmlGrapesjs, true);
        }
    }

    function getSource(t, applyDjangoTag, postfixId) {
        elementBlock = document.getElementById("gjs-" + postfixId).children[0];
        elementBlock.setAttribute(
            "style",
            "pointer-events: none; background:#0000; z-index:100; opacity:0.4; filter:alpha(opacity=50)"
        );
        editor = this["editor_"+ postfixId];

        django.jQuery.ajax({
            url: "{% url 'admin:dgjs_get_template' %}",
            data: {
                "template_name": t.value,
                "apply_django_tag": applyDjangoTag
            },

            success: function(data){
                editor.setComponents(
                    replaceTag(
                        normalizeData(data),
                        replaceTagsInit
                    )
                );
                elementBlock.removeAttribute('style')
            }
        });
    }

    (function($) {
        $('input[name="_save"]').on('click', function() {
            setHtmlInTheField()
        });
        $('input[name="_continue"]').on('click', function() {
            setHtmlInTheField()
        });
        $('input[name="_addanother"]').on('click', function() {
            setHtmlInTheField()
        });
    })(django.jQuery);
</script>
{% endblock %}

{% block extrastyle %}
{{ block.super }}

<link rel="stylesheet" href="{% static 'garpix_page/css/admin/clone_styles.css' %}">
<script src="{% static 'garpix_page/js/admin/clone.js' %}"></script>

{% endblock %}

{% block object-tools %}
{{ block.super }}
<div class="submit-row">
    {{ object }}
    <a href="#openModal" class="default submit-row-new_choice button">Клонировать компонент</a>
</div>

<div id="openModal" class="modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Клонирование</h3>
                <a href="#modal-close" title="Close" class="modal-close">×</a>
            </div>
            {% if original %}
            <div class="modal-body">
                <form action="{% url 'admin:garpix_page_basecomponent_full_clone' original.id %}" method="POST" enctype="multipart/form-data">
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="component__title">Введите новое название (опционально):</label><br>
                        <input type="text" class="form-control" id="component__title" name="title">
                    </div>
                    <input type="submit" class="default submit-row-new_choice" value="Клонировать">
                </form>
            </div>
            {% endif %}
        </div>
    </div>
</div>

{% endblock %}
