{% extends "timeline-page.html" %}

{% block main_body %}

<style>
    #test-stimulus {
        font-weight: bold;
    }
</style>

<div id="test" style="position: relative; text-align: center">
    <div class="d-flex justify-content-center">
    <div class="spinner-grow" role="status">
        <span class="visually-hidden">Loading...</span>
    </div>
    </div>
</div>
<script src="/static/scripts/fitty.min.js"></script>
<script>
    $.fn.extend({
        disableSelection: function () {
            this.each(function () {
                if (typeof this.onselectstart !== 'undefined') {
                    this.onselectstart = function () {
                        return false;
                    };
                } else if (typeof this.style.MozUserSelect !== 'undefined') {
                    this.style.MozUserSelect = 'none';
                } else {
                    this.onmousedown = function () {
                        return false;
                    };
                }
            });
        }
    });

    (function (window, factory) {
        if (typeof define === 'function' && define.amd) {
            return define(['jquery'], function (jQuery) {
                return window.VocabTest = factory(jQuery);
            });
        } else if (typeof exports === 'object') {
            return module.exports = factory(require('jquery'));
        } else {
            return window.VocabTest = factory(window.jQuery);
        }
    })
    (window, function ($) {
        var VocabTest, document;
        document = window.document;
        VocabTest = (function () {
            function VocabTest(options) {
                this._options = $.extend({
                    items: undefined,
                    containerID: '',
                    history: [],
                    lagBetweenTrials: 200,
                    displayTime: 1000,
                    showButtons: true,
                    useKeyboard: true,
                    trueLabelTemplate: '<strong>True</strong>',
                    falseLabelTemplate: '<strong>False</strong>',
                    pressKeyLabelTemplate: ', press <kbd>{KEY}</kbd>',
                    trueLabelStyle: undefined,
                    falseLabelStyle: undefined,
                    trueKeyLabel: 'A',
                    trueKey: 'KeyA',
                    falseKeyLabel: 'L',
                    falseKey: 'KeyL',
                    allowRevisitingItems: false,
                    onEnd: function (tour) {
                    },
                }, options);
                var test = this;
                test.startTime = performance.now();

                if (test._options.items !== undefined && test._options.items.length === 0) {
                    throw new Error('No items provided');
                }
                if (test._options.containerID === '') {
                    throw new Error('No container ID specified');
                }

                if (!test._options.showButtons && !test._options.useKeyboard) {
                    throw new Error('Either showButtons or useKeyboard must be true');
                }


                test.history = [];
                test.visitedIDs = [];
                test.items = test._options.items;
                test.trialCount = 1;
                test.allowRevisitingItems = test._options.allowRevisitingItems;
                test.finished = false;

                ['trueLabelStyle', 'falseLabelStyle'].forEach(function (key) {
                    if (test._options[key] === undefined) {
                        var float = key.startsWith('true') ? 'float-start float-left' : 'float-end float-right';
                        var color = key.startsWith('true') ? 'success' : 'danger';
                        if (test._options.showButtons) {
                            test._options[key] = float + ' btn btn-' + color;
                        } else {
                            test._options[key] = float + ' text-' + color;
                        }
                    }
                });

            }

            VocabTest.prototype.renderTemplate = function (onClickEvent, style, id, textLabel, key, keyLabel) {
                keyLabel = keyLabel.replace('{KEY}', key);
                if (onClickEvent === undefined) {
                    return '<span class="' + style + '" id="' + id + '">' + textLabel + keyLabel + '</span>';
                } else {
                    return '<button onclick="' + onClickEvent + '" class="' + style + '" id="' + id + '">' + textLabel + keyLabel + '</button>';
                }

            };

            VocabTest.prototype.start = async function () {
                var test = this;
                test.items.forEach(function (item, id) {
                    item.id = id;
                });

                var controls = test.renderTemplate(
                    test._options.showButtons ? "test.nextTrial('real')" : undefined,
                    test._options.trueLabelStyle,
                    'wiki-vocab-real-word',
                    test._options.trueLabelTemplate,
                    test._options.trueKeyLabel,
                    test._options.pressKeyLabelTemplate
                ) + test.renderTemplate(
                    test._options.showButtons ? "test.nextTrial('fake')" : undefined,
                    test._options.falseLabelStyle,
                    'wiki-vocab-fake-word',
                    test._options.falseLabelTemplate,
                    test._options.falseKeyLabel,
                    test._options.pressKeyLabelTemplate
                );
                $('#' + test._options.containerID).html('<div class="text-center" onselectstart="return false" style="height: 70vh;" id="test-stimulus"></div>' +
                    '<div id="test-controls">' + controls + '</div>');

                if (test._options.useKeyboard) {
                    var availableKeys = [test._options.trueKey, test._options.falseKey];
                    $(document).on("keypress", function (e) {
                        var key = e.originalEvent.code;

                        if (availableKeys.includes(key)) {
                            if (key === test._options.trueKey) {
                                test.nextTrial('real');
                            } else if (key === test._options.falseKey) {
                                test.nextTrial('fake');
                            }
                        }
                    });
                }
                test.showTrial();
            };


            VocabTest.prototype.prepareTrial = function () {
                var test = this,
                    availablePairs = [];

                test.items.forEach(function (item) {
                    if (!(test.allowRevisitingItems === false && test.visitedIDs.includes(item.id))) {
                        availablePairs.push(item);
                    }
                });

                test.currentItem = test.items[test.trialCount - 1]
                test.currentItem = JSON.parse(JSON.stringify(test.currentItem));

                test.visitedIDs.push(test.currentItem.id);
            };


            VocabTest.prototype.showTrial = function () {
                var test = this;
                if (test.trialCount > test.items.length) {
                    test.finish();
                    return true;
                }

                test.prepareTrial();

                var stimulusContainer = $('#test-stimulus');
                if (test._options.presentAsImage) {
                    var imageKey = test.currentItem.hash;
                    var url = psynet.media.data.image[imageKey].url;
                    var maxImageWidth = test._options.maxWidth,
                        maxImageHeight = test._options.maxHeight;
                    stimulusContainer.html('<img src="' + url + '" style="width: 100%; height: auto; max-width: ' + maxImageWidth + 'px; max-height: ' + maxImageHeight + 'px;">');
                } else {
                    stimulusContainer.text(test.currentItem.stimulus);
                    fitty('#test-stimulus', {maxSize: 80});
                }
                test.startTrialTime = performance.now();
                test.timeOut = setTimeout(function () {
                    stimulusContainer.html();
                    stimulusContainer.text('…');
                }, test._options.displayTime);
            };

            VocabTest.prototype.finish = function () {
                var test = this;
                test.finished = true;
                var container = $('#' + test._options.containerID);
                container.empty();
                console.debug('Test took ' + performance.now() - test.startTime);
                test._options.onEnd(test);
            };


            VocabTest.prototype.nextTrial = function (answer) {
                var test = this;
                var timeTaken = performance.now() - test.startTrialTime;
                clearTimeout(test.timeOut);

                if (!test.finished) {
                    test.timeOut = setTimeout(function () {
                        test.currentItem.answer = answer;
                        test.currentItem.timeTaken = timeTaken;
                        test.history.push(test.currentItem);
                        test.trialCount++;
                        test.showTrial();

                    }, test._options.lagBetweenTrials);
                }
            };


            return VocabTest;

        })();
        return VocabTest;
    });


    var test = new VocabTest({
        items: items,
        containerID: 'test',
        displayTime: testConfig.displayTime,
        trueKey: testConfig.trueKey,
        trueKeyLabel: testConfig.trueKeyLabel,
        falseKey: testConfig.falseKey,
        falseKeyLabel: testConfig.falseKeyLabel,
        trueLabelTemplate: testConfig.trueLabelTemplate,
        falseLabelTemplate: testConfig.falseLabelTemplate,
        pressKeyLabelTemplate: testConfig.pressKeyLabelTemplate,
        lagBetweenTrials: testConfig.lagBetweenTrials,
        showButtons: testConfig.showButtons,
        useKeyboard: testConfig.useKeyboard,
        maxWidth: testConfig.imageWidth,
        maxHeigth: testConfig.imageHeight,
        presentAsImage: testConfig.presentAsImage,

        onEnd: function (test) {
            psynet.nextPage(test.history);
        }
    });

    psynet.trial.onEvent("submitEnable", function () {
        test.start();
    });
</script>
{% endblock %}
