{% extends "base.html" %}

{% block title %}Version history{% endblock %}

{% import 'json_diff_macro.html' as json_diff %}

{% block headerEnd %}

{{ json_diff.header() }}

{% endblock %}


{% block content %}
    <h1>Version history</h1> <br>

    <select id="fid">
    {% for fid in fids | sort() %}
        <option value="{{ fid }}">{{ fid }}</option>
    {% endfor %}
    </select>

    <select id="locale">
    {% for locale in locales %}
        <option value="{{ locale }}">{{ locale }}</option>
    {% endfor %}
    </select>

    <button onclick="fetchHistory()">Fetch history</button>

    <br>
    Left panel: <select id="history_id_1"></select> <button onclick="uploadRevisionToPwnDoc('history_id_1')">Upload revision for comparison in PwnDoc</button><br>
    Right panel: <select id="history_id_2"></select> <button onclick="uploadRevisionToPwnDoc('history_id_2')">Upload revision for comparison in PwnDoc</button><br>

    <br>
    <button onclick="fetchVersions()">Download selected version for comparison</button>


    {{ json_diff.body() }}

<script>

var version1_field_id = 'history_id_1';
var version2_field_id = 'history_id_2';

function format_time(seconds) {
    return new Date(seconds * 1000).toISOString();
}

function add_options(elem_id, options){
    let optionList = document.getElementById(elem_id).options;
    while (optionList.length){
        optionList.remove(0);
    }

    options.forEach(option =>
        optionList.add(
            new Option(option.text, option.value, option.selected)
        )
    );
}

// https://stackoverflow.com/a/50331141
function checkFetchErrors(response) {
    if (response.ok){ return response; }
    // alert("Request error.");
    throw new Error(response.status);
}

function fetchHistory() {
    let fid = $("#fid").val();
    let locale = $("#locale").val();
    // console.log(fid, locale);
    fetch(`/import_automator/templates/all_versions/${fid}/${locale}`)
        .then(checkFetchErrors)
        .then(response => response.json())
        .then(data => {
            // console.log(JSON.stringify(data));
            let options = [];

            if (data.length == 0){
                alert(`There are no revisions for fid ${fid} and locale ${locale}.`);
                return;
            }

            // let title = data.slice(-1)[0]?.data?.title;
            for (const single_history of data) {
                // console.log(single_history);
                let time = format_time(single_history.timestamp);
                let history_id = single_history.history_id;
                options.push({'text': `${time} (${history_id})`, 'value': history_id, 'selected': false});
            }
            add_options(version1_field_id, options);
            add_options(version2_field_id, options);
        })
}


function setHistoryTextBasedOnSelectField(historySelectID, textAreaID){
    let fid = $("#fid").val();
    let locale = $("#locale").val();

    let history_id = document.getElementById(historySelectID).value;

    return fetch(`/import_automator/templates/version/${history_id}`)
        .then(checkFetchErrors)
        .then(response => response.text())
        .then(data_text => {
            // todo: this gets called even after fail
            document.getElementById(textAreaID).value = data_text;
        })

}

function fetchVersions() {
    // db history update happens on page load, not on request load
    setHistoryTextBasedOnSelectField('history_id_1', 'textarealeft')
        .then(() => {
            setHistoryTextBasedOnSelectField('history_id_2', 'textarearight');
        });
}

function uploadRevisionToPwnDoc(historySelectID) {
    let history_id = document.getElementById(historySelectID).value;
    return fetch(`/import_automator/templates/version_to_pwndoc/${history_id}`)
        .then((response) => {
            if (response.ok) {
                alert("Revision uploaded to PwnDoc, check it in its UI.");
            }
        })
        .catch(function (error) {
	        console.warn(error);
	        alert("Upload failed");
        })
}

</script>


{% endblock %}