{% extends "base.html" %}

{% block title %}Edit JSON{% endblock %}

{% block headerEnd %}
{% endblock %}

{% block content %}

    <label for="templateList">Templates:</label>
    <select id="templateList" style="width: 500px;">
        {% for value in templates %}
            {% set templatePrintableName = '' if value.title.startswith('AUTOGENERATED_TITLE:') else value.title %}
            <option value="{{ value.fid }}" printableName="{{ templatePrintableName }}">{{ value.fid }}: {{ templatePrintableName }}</option>
        {% endfor %}
    </select>
    Copy to cliboard:
    <button id="templateListCopyFidButton">FID</button>
    <button id="templateListCopyJSONButton">JSON line</button>

    <hr>

    <label for="filesList">Which file to interact with:</label>
    <select id="filesList" style="width: 500px;">
      {% for value in files %}
        <option value="{{ value[0] }}">{{ value[1] }}</option>
      {% endfor %}
    </select>

    <p>
      <button id="loadFile">Load file from server</button>
      <button id="saveFile">Save file to server</button>
    </p>
    <div id="jsoneditor" style="width: 80vw; height: 70vh; position: absolute; left: 10vw;"></div>

    <script type="module">
        function getSelectedFile() {
            return $('#filesList').select2('data')[0].id;
        }

        function getSelectedTemplateFid() {
            return $('#templateList').select2('data')[0].id;
        }

        function getSelectedTemplateJSON() {
            let fid = getSelectedTemplateFid();
            let printableName = $('#templateList').select2('data')[0].element.getAttribute("printableName");
            return `{ "id": "${fid}", "#name": "${printableName}" },`;
        }

        function copy(text) {
            navigator.permissions.query({name: "clipboard-write"}).then(result => {
                if (!(result.state === "granted" || result.state === "prompt")) {
                    console.warn("Clipboard permission or API fail");
                    return;
                }

                navigator.clipboard.writeText(text).then(function () {
                    // success
                }, function () {
                    console.warn("Clipboard write fail")
                });

            });
        }

        $(document).ready(function() {
            $('#filesList').select2();
            $('#templateList').select2();
            document.querySelector('#templateListCopyFidButton').addEventListener('click', function() {
                    copy(getSelectedTemplateFid());
                }
            );
            document.querySelector('#templateListCopyJSONButton').addEventListener('click', function() {
                    copy(getSelectedTemplateJSON());
                }
            );
        });

    // https://www.jsdelivr.com/package/npm/svelte-jsoneditor
        import {
            JSONEditor
        } from '{{ url_for('static', filename='npm/jsoneditor0.3.49.js') }}'

        // create the editor
        const editor = new JSONEditor({
            target: document.getElementById('jsoneditor'),
            props: {
                mode: 'code'
            }
        })

        // set json
        document.getElementById('loadFile').onclick = function() {

            const selectedFilename = getSelectedFile();

            fetch('{{ url_for("api_root.get_versioned_file", filename="") }}/' + selectedFilename)
                .then(response => {
                    if (!response.ok) {
                        throw Error(response.statusText);
                    }
                    return response.text();
                })
                .then(data => {
                    console.log(data);

                    const content = {
                        text: data, // used in code mode
                        json: undefined
                    }
                    editor.set(content);

                });
        }

        // get json
        document.getElementById('saveFile').onclick = function() {
            const selectedFilename = getSelectedFile();

            const content = editor.get();
            // alert(JSON.stringify(content, null, 2));

            fetch('{{ url_for("api_root.upload_versioned_file", filename="") }}/' + selectedFilename, {
                method: 'post',
                body: content.text,
            })
        }
    </script>


{% endblock %}