{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HyperEditor</title>

    <link rel="stylesheet" href="{% static 'hypereditor/hyper_editor.css' %}" />

    {% for st in user_stylesheets %}
        <link rel="stylesheet" href="{% static st %}" />
    {% endfor %}
</head>
<body>

    <!-- Hyper Editor Loads here -->
    <div id="hyperEditor"></div>

    <script type="text/javascript" src="{% static 'hypereditor/hyper_editor.js' %}"></script>

    <script type="text/javascript">

        /**
         * Helper function to get value by key from cookie
         * @param name: string
         * @returns any
         */
        function get_cookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i].trim();
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        /**
         * Helper function to parse query params from string
         * @param query: str
         * @returns str
         */
        function parse_query_string(query) {
            var vars = query.split("&");
            var query_string = {};
            for (var i = 0; i < vars.length; i++) {
              var pair = vars[i].split("=");
              var key = decodeURIComponent(pair[0]);
              var value = decodeURIComponent(pair[1]);
              // If first entry with this name
              if (typeof query_string[key] === "undefined") {
                query_string[key] = decodeURIComponent(value);
                // If second entry with this name
              } else if (typeof query_string[key] === "string") {
                var arr = [query_string[key], decodeURIComponent(value)];
                query_string[key] = arr;
                // If third or later entry with this name
              } else {
                query_string[key].push(decodeURIComponent(value));
              }
            }
            return query_string;
        }

        /**
         * Renders preview for a block. Global for all blocks.
         * @param value: obj - block value
         * @param callback: a function to send back response to caller
         */
        function async_preview(value, callback) {
            fetch('{% url "hypereditor:preview" %}', {
                credentials: "same-origin",
                method: 'POST',
                headers: {
                    'Accept': 'application/json, text/plain, */*',
                    'X-CSRFToken': get_cookie('csrftoken'),
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
                },
                body: JSON.stringify(value)
            }).then(response => response.text())
            .then(data => {
                callback(data)
            })
        }


        //JavaScript Variables Provided by Registered Blocks
        {{ js_variables|safe }}


        var urlParams = parse_query_string(window.location.href.split('?')[1])

        // if origin not set then set it. otherwise iframe messaging might not trusted by browser
        if (!window.location.origin) {
            window.location.origin = window.location.protocol + "//"
                + window.location.hostname
                + (window.location.port ? ':' + window.location.port : '');
        }


        // create instance of hyper editor
        hyperEditor = new HyperEditor('#hyperEditor', {
            imageSearchApi: "#", // image search does not work for now
            preview: async_preview {% if block_settings %}, blocks: JSON.parse('{{ block_settings|safe }}') {% endif %}
        })
    </script>

    <!-- Load JS Block files if any -->
    {% for js_plugin in js_plugins %}
    <script src="{% static js_plugin %}"></script>
    {% endfor %}

    <!- generate simpler blocks -->
    <script type="text/javascript" src="{% url 'hypereditor:blocks' %}"></script>

    <script type="text/javascript">

        function bindEvent(element, eventName, eventHandler) {
            if (element.addEventListener) {
                element.addEventListener(eventName, eventHandler, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + eventName, eventHandler);
            }
        }

        bindEvent(window, 'message', function (e) {
            if (e.data && e.data.id == urlParams.id) {
                try {
                    var data_to_init = JSON.parse(e.data.state)
                    init_hyper_editor(JSON.parse(e.data.state))
                } catch(err) {
                    init_hyper_editor([])
                }
            }
        });

        init_hyper_editor = function (state = []) {
            if (!state && !(state instanceof Array)) state = []

            initial_state = state

            hyperEditor.initialize(initial_state)

            hyperEditor.addStateChangeListener(function (state) {
                window.parent.postMessage({
                    id: urlParams.id,
                    state: JSON.stringify(state)
                }, window.location.origin)
            })

        }
    </script>

</body>
</html>