{% extends '_layout.html' %}

{% block styles %}
    {{ super() }}
    <link rel="stylesheet" href="/static/styles/annotator.css">
{% endblock %}

{% block content %}
    {% if document is not none %}
        <div class="columns">
            <div class="column">
                <a href="/projects/{{ project.id }}" class="button is-info is-outlined is-pulled-left">
                    <i class="fas fa-tasks mr-1"></i><span>Project</span>
                </a>
                <a id="nextButton" href="javascript:void(0)" class="button is-primary is-outlined is-pulled-right"
                   onclick="submit(null)">
                    <span>Next</span><i class="fas fa-arrow-circle-right pl-1"></i></a>
            </div>
        </div>
        {% if project.render_header(document) is not none %}
            <div class="columns">
                <div class="column">
                    <div class="box">
                        {{ project.render_header(document) | safe }}
                    </div>
                </div>
            </div>
        {% endif %}
        <div class="columns">
            <div class="column">
                <div class="box">
                    {% if project.type == 'sequence_labeling' %}
                        <div class="annotator-div is-family-primary is-size-4" id="annotationField"></div>
                    {% else %}
                        <div class="block">
                            <p class="subtitle">{{ document.text | safe }}</p>
                        </div>
                        <div class="block">
                            <div class="field">
                                {% for ll in project.labels %}
                                    <label class="checkbox">
                                        <input type="checkbox"
                                               value={{ ll.value }} id="option_{{ ll.value }}"
                                               onchange="submit(getLabel('{{ ll.value }}'))">
                                        {{ ll.label }}
                                    </label>
                                {% endfor %}
                            </div>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    {% else %}
        <div class="container">
            <div class="columns">
                <div class="column is-half is-offset-one-quarter">
                    <div class="box">
                        <h1 class="title">Congratulations!</h1>
                        <div class="block">
                            <p>We do not have any more documents for you to annotate now. We will let you know if we
                                need your help again.</p>
                        </div>
                        <h2 class="subtitle">Thank you for your contribution.</h2>
                    </div>
                </div>
            </div>
        </div>
    {% endif %}
{% endblock %}

{% block scripts %}
    {{ super() }}
    <script src="/static/scripts/annotator.js"></script>
    <!--suppress JSUnresolvedFunction, JSUnresolvedVariable -->
    {% if document is not none %}
        <script>
            // collection of URL endpoints
            const url_of = {
                annotations_api: '{{ url_for('annotate_view.get_annotations', project_id = project.id, document_id = document.id) }}',
                annotate_next: '{{ url_for('annotate_view.annotate_next', project_id = project.id) }}',
            };

            const documentText = '{{ document.text | safe }}';

            const projectType = '{{ project.type }}';

            const labelOptions = JSON.parse('{{ options | safe }}');

            let annotator = null;

            function loading(state = true) {
                let nextButton = document.getElementById('nextButton');
                if (state) {
                    nextButton.classList.add('is-loading');
                } else {
                    nextButton.classList.remove('is-loading');
                }
            }

            /**
             * Gets status of checkbox indicated by provided label ident
             *
             * @param id: label id
             */
            function getLabel(id) {
                let checkbox = $('#option_' + id);
                return {value: checkbox.val(), status: checkbox.prop('checked')};
            }

            /**
             * Submit data to server
             *
             * @param data: JSON data
             * @param type: type of submission; options: (label, annotation)
             * @param method: method to use for submission; options: (POST, DELETE)
             */
            function submit(data, type = 'label', method = 'POST') {
                loading();
                let temp = {};
                let target = url_of.annotate_next;
                if (data !== null) {
                    temp = {data, type};
                    target = null;
                }
                $.ajax({
                    type: method,
                    url: url_of.annotations_api,
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(temp),
                    success: function (data) {
                        loading(false);
                        refresh(target);
                    },
                });
            }

            /**
             * Update annotations
             */
            function refreshAnnotations() {
                loading();
                $.get(url_of.annotations_api).then(
                    (data) => {
                        let annotations = data.data;
                        annotator.setAnnotations(annotations);
                        loading(false);
                    }
                ).catch((error) => {
                    console.log(error);
                });
            }

            /**
             * Refresh page
             *
             * @param target:
             */
            function refresh(target) {
                if (target === null) {
                    refreshAnnotations();
                } else {
                    window.location.href = target;
                }
            }

            /**
             * Initialize page
             */
            function initialize() {
                if (projectType === 'sequence_labeling') {
                    // set new annotator
                    annotator = new Annotator('annotationField', documentText, labelOptions);
                    // listen to events - delete
                    annotator.addEventListener('delete', (annotation) => {
                        submit(annotation, 'annotation', 'DELETE');
                    });
                    // listen to events - update
                    annotator.addEventListener('update', (annotation, value) => {
                        annotation.label = value;
                        submit(annotation, 'annotation');
                    });
                    // initialize annotator
                    annotator.initialize();
                } else {
                    annotator = {
                        setAnnotations: function (annotations) {
                            let checkedLabels = [];
                            for (let ak in annotations) {
                                let lv = annotations[ak].label;
                                checkedLabels.push(lv);
                            }
                            for (let lk in labelOptions) {
                                let lv = labelOptions[lk].value;
                                let checkbox = $('#option_' + lv);
                                if (checkedLabels.includes(lv)) {
                                    checkbox.prop('checked', true);
                                } else {
                                    checkbox.prop('checked', false);
                                }
                            }

                        }
                    }
                }
                // refresh page
                refresh(null);
            }

            /**
             * Initialize when document is ready
             */
            $(document).ready(initialize);
        </script>
    {% endif %}
{% endblock %}