// .. Copyright (C) 2017 Bryan A. Jones.
//
//    This file is part of E-Book Binder.
//
//    E-Book Binder is free software: you can redistribute it and/or modify it
//    under the terms of the GNU General Public License as published by the Free
//    Software Foundation, either version 3 of the License, or (at your option)
//    any later version.
//
//    E-Book Binder is distributed in the hope that it will be useful, but WITHOUT
//    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
//    FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
//    details.
//
//    You should have received a copy of the GNU General Public License along
//    with E-Book Binder.  If not, see <http://www.gnu.org/licenses/>.
//
// .. highlight:: javascript
//
// **************************************************************************************
// |docname| - JavaScript functions supporting immediate feedback to in-browser questions
// **************************************************************************************

"use strict";

import RunestoneBase from "../../common/js/runestonebase";
import CodeMirror from "codemirror";
import "codemirror/mode/gas/gas.js";
import "codemirror/mode/python/python.js";
import "codemirror/mode/javascript/javascript.js";
import "codemirror/mode/sql/sql.js";
import "codemirror/mode/clike/clike.js";
import "codemirror/mode/octave/octave.js";
import "codemirror/lib/codemirror.css";

// Constructor
// ===========
// Object containing all instances of LP problems. (I assume there is just one per page.)
window.LPList = {};

// FITB constructor
class LP extends RunestoneBase {
    constructor(opts) {
        super(opts);
        this.useRunestoneServices = opts.useRunestoneServices;
        // Store the DOM element (the input) for the "Test" button.
        this.element = opts.orig;
        this.containerDiv = this.element;
        this.divid = this.element.id;
        // Store the DOM element (the textarea) where compile results will be displayed.
        this.resultElement = $(this.element).siblings("textarea");
        // Store the DOM element (a span) where feedback will be displayed.
        this.feedbackElement = $(this.element).siblings("div");
        // Use a nice editor.
        let that = this;
        this.textAreas = [];
        $(".code_snippet").each(function (index, element) {
            let editor = CodeMirror.fromTextArea(element, {
                lineNumbers: true,
                mode: $(that.element).attr("data-lang"),
                indentUnit: 4,
                matchBrackets: true,
                autoMatchParens: true,
                extraKeys: { Tab: "indentMore", "Shift-Tab": "indentLess" },
            });
            // Make the editor resizable.
            $(editor.getWrapperElement()).resizable({
                resize: function () {
                    editor.setSize($(this).width(), $(this).height());
                    editor.refresh();
                },
            });
            // Keep track of it.
            that.textAreas.push(editor);
        });
        // Handle clicks to the "Save and run" button.
        $(this.element).click((eventObject) => that.onSaveAndRun(eventObject).then(null));
        this.checkServer("lp_build", true);
    }

    async onSaveAndRun(_eventObject) {
        $(this.resultElement).val("Building...");
        $(this.feedbackElement).text("").attr("");
        // Since the Save and run button was clicked, we assume the code snippets have been changed; therefore, don't store ``correct`` or ``answer.resultString`` because they are out of date.
        let answer = { code_snippets: this.textareasToData() };
        this.setLocalStorage({
            answer: answer,
            timestamp: new Date(),
        });
        // Store the answer that the server returns, which includes additional data (correct/incorrect, feedback from the build, etc.).
        let serverAnswer;
        try {
            serverAnswer = await this.logBookEvent({
                event: "lp_build",
                // All values must be strings, or the resulting values on the server side come out confused.
                answer: JSON.stringify(answer),
                // Find the relative path to this web page. Slice off the leading ``/``.
                path: window.location.href
                    .replace(eBookConfig.app, "")
                    .slice(1),
                div_id: this.divid,
            });
        } catch (err) {
            $(this.feedbackElement)
                .val(`Error contacting server: {err}.`)
                .attr("class", "alert alert-danger");
            return;
        }
        // The server doesn't return the ``code_snippets``, for efficiency. Include those. If an error was returned, note that there is no ``answer`` yet.
        if (!("answer" in serverAnswer)) {
            serverAnswer["answer"] = {};
        }
        serverAnswer["answer"]["code_snippets"] = this.textareasToData();
        this.displayAnswer(serverAnswer);
        this.setLocalStorage(serverAnswer);
    }

    // Given a single answer, display it.
    displayAnswer(data) {
        if ("errors" in data) {
            // Display any server-side errors. If this key is present, other keys won't be.
            $(this.feedbackElement)
                .text(data.errors.join("<br>"))
                .attr("class", "alert alert-danger");
        } else {
            // Display and color-code the results.
            $(this.resultElement).val(data.answer.resultString);
            if (data.correct == null) {
                $(this.feedbackElement)
                    .text("Response recorded.")
                    .attr("class", "alert alert-success");
            } else if (data.correct >= 100) {
                $(this.feedbackElement)
                    .text("Correct. Grade: " + data.correct + "%")
                    .attr("class", "alert alert-success");
            } else {
                $(this.feedbackElement)
                    .text("Incorrect. Grade: " + data.correct + "%")
                    .attr("class", "alert alert-danger");
            }
            // Scroll to the bottom of the results.
            $(this.resultElement).scrollTop(this.resultElement[0].scrollHeight);
        }
    }
    // Store the contents of each textarea into an array of strings.
    textareasToData() {
        return $.map(this.textAreas, function (obj, index) {
            // See https://codemirror.net/doc/manual.html#api.
            return obj.getValue();
        });
    }
    // Store an array of strings in ``data.code_snippets`` into each textarea.
    dataToTextareas(data) {
        // Find all code snippet textareas.
        $(this.textAreas).each(function (index, value) {
            // Silently ignore if ``data.answer.code_snippets`` or ``data.answer.code_snippets[index]`` isn't defined.
            value.setValue((data.answer.code_snippets || "")[index] || "");
        });
    }
    // Restore answers from storage retrieval done in RunestoneBase.
    restoreAnswers(data) {
        this.dataToTextareas(data);
        this.displayAnswer(data);
    }
    checkLocalStorage() {
        // Loads previous answers from local storage if they exist.
        var storedData;
        if (localStorage.length > 0) {
            var key = this.localStorageKey();
            var ex = localStorage.getItem(key);
            if (ex !== null) {
                try {
                    storedData = JSON.parse(ex);
                } catch (err) {
                    // error while parsing; likely due to bad value stored in storage
                    console.log(err.message);
                    localStorage.removeItem(key);
                    return;
                }
                this.restoreAnswers(storedData);
            }
        }
    }
    setLocalStorage(data) {
        localStorage.setItem(this.localStorageKey(), JSON.stringify(data));
    }
}

// Initialization
// ==============
// Find the custom HTML tags and execute our code on them.
$(document).bind("runestone:login-complete", function () {
    $("[data-component=lp_build]").each(function (index) {
        try {
            LPList[this.id] = new LP({
                orig: this,
                useRunestoneServices: eBookConfig.useRunestoneServices,
            });
        } catch (err) {
            console.log(`Error rendering LP Problem ${this.id}`);
        }
    });
});

if (typeof window.component_factory === "undefined") {
    window.component_factory = {};
}
window.component_factory["lp_build"] = function (opts) {
    return new LP(opts);
};
