ID_MAX = 68;
POSSIBLE_FLAVOURTEXTS = [
    "Sieni elää symbioosissa, eli ns. verkossa.",
    "Viikingit söivät kärpässieniä saavuttaakseen raivoisan taisteluvireen.",
    "Sieni.us saattaa aiheuttaa pysyvää vahinkoa mielenterveydelle liikaa nautittuna.",
    "Sieni ei ole kasvi.",
    "Sieni ei ole eläin.",
    "Kärpässienet aiheuttavat aistiharhoja.",
    'Todellisuus on vain <a href="https://fi.wikipedia.org/wiki/Psilosybiini">psilosybiinin</a> puutteesta johtuva illuusio.'
];
RUFFLE_WIP_ERR = '<p>Ruffle ei vielä tue tämän id:n .swf tiedostoa tarpeeksi näyttääkseen sen oikein.</p> \
                    <p>Lue <a href="/info.html#issues">infosivulta</a> rufflen ongelmista tarkemmin.</p> ';
ISSUES = [35, 41, 43, 50, 60, 68];
CURRENT_SWF = null;
LAST_LOADED_SWF = null;


/////////////////// Initializing & Generic stuff

// Called on document.onload by definition in html document:
// <body onload="on_load()">
function on_load() {
    player = window["player"];
    let is_info = (window.location.pathname === "/info.html");
    make_links_spa();

    if (!is_info) {
        on_load_index();
    }

    window.onpopstate = e => {
        if (player.instance && window.location.pathname === "/") {
            load_current_id();
        } else {
            load_page_spa(location.toString());
        }
    };
}

// on_load index.html
function on_load_index() {
    window.RufflePlayer = window.RufflePlayer || {};
    window.RufflePlayer.config =
    {
        "public_path": "/js/ruffle/ruffle.js"
    };

    let ruffle = window.RufflePlayer.newest();
    player = ruffle.create_player();
    let ruffle_container = document.getElementById("ruffle-container");
    ruffle_container.appendChild(player);

    context = new AudioContext();
    context.resume().then(_ => {
        document.getElementById("audio-test").innerHTML = "";
    }).catch(e => {
        console.log("Failure : " + e);
    });

    setInterval(_ => {
        if (LAST_LOADED_SWF !== CURRENT_SWF) {
            LAST_LOADED_SWF = CURRENT_SWF;
            if (CURRENT_SWF) {
                load_and_play(CURRENT_SWF);
            }
        }
    }, 100);

    load_current_id();
    document.onkeypress = try_resume;
    document.onmousedown = try_resume;
}

function set_error(message) {
    document.getElementById("error").innerHTML = "";
    console.log(message);
    if (message) {
        var template = document.createElement('template');
        template.innerHTML = message;
        document.getElementById("error").append(template.content);
    }
}

function set_flavourtext(flavourtext) {
    var template = document.createElement('template');
    template.innerHTML = flavourtext;
    document.getElementById("flavourtext").innerHTML = "";
    document.getElementById("flavourtext").append(template.content);
}


/////////////////// SPA (single-page-application) stuff 

// Load a page as spa
function load_page_spa(url) {
    let request = new XMLHttpRequest();
    request.addEventListener("loadend", _ => {
        CURRENT_SWF = null;

        document.onkeypress = _ => { };
        document.onmousedown = _ => { };

        let parser = new DOMParser();
        let new_document = parser.parseFromString(request.responseText, "text/html");

        document.title = new_document.title;
        document.body = new_document.body;

        window.history.pushState(url, url, url);

        on_load();
    });
    console.log("get " + url);
    request.open("GET", url);
    request.send();
}

// Make all elements with class "spa" be spa'd links
function make_links_spa() {
    let elems = document.getElementsByClassName("spa");
    for (i = 0; i < elems.length; i++) {
        let elem = elems[i];
        url = elem.href;
        elem.onclick = e => {
            e.preventDefault();
            load_page_spa(url);
        }
    }
}

// Load the given id as spa. Assumes we are on index.html already
function load_id_spa(id) {
    let new_url = window.location.protocol + ":/" + window.location.host + "/?id=" + id;
    console.log(new_url);
    window.history.pushState(new_url, new_url, "/?id=" + id);
    load_current_id();
}


/////////////////// Ruffle stuff

// Get current id, or random id if no id can be found
function current_id() {
    let id = null;
    search = window.location.search.split("=");
    if (search[0] === "?id" && search.length > 1) {
        id = parseInt(search[1]);
    }
    return try_get_id(id, null);
}

// Returns id if id is valid, otherwise increments increment to it, or chooses a random id if increment is null
// Skip id's with issues
function try_get_id(id, increment) {
    let returned = id;

    if (id === null || isNaN(id) || id < 0 || id > ID_MAX) {
        returned = get_random_id();
    } else {
        if (increment) {
            returned = (id + increment + ID_MAX + 1) % (ID_MAX + 1);
        }
    }

    while (ISSUES.includes(returned) && increment) {
        returned = (returned + increment + ID_MAX + 1) % (ID_MAX + 1);
    }

    return returned;
}

// Get an entirely random id, but skip id's with issues
function get_random_id() {
    let random_id = Math.floor(Math.random() * (ID_MAX + 1));
    while (ISSUES.includes(random_id)) {
        random_id = Math.floor(Math.random() * (ID_MAX + 1));
    }
    return random_id;
}

// Load the swf with current_id(), and set_up_link() previous, random and next
function load_current_id() {
    let flavourtext = POSSIBLE_FLAVOURTEXTS[Math.floor(Math.random() * POSSIBLE_FLAVOURTEXTS.length)].trim();
    set_flavourtext(flavourtext);

    let id = current_id();
    let url = swf_url(id);

    let error = null;
    if (ISSUES.includes(id)) {
        error = RUFFLE_WIP_ERR;
    }
    set_error(error);

    CURRENT_SWF = url;

    let previous_id = try_get_id(id, -1);
    let next_id = try_get_id(id, 1);
    let random_id = get_random_id();
    set_up_link("previous", previous_id);
    set_up_link("random", random_id);
    set_up_link("next", next_id);
}

// Set up the link at id elem_id, so it's href points at /?id=[id], and update it's onclick
function set_up_link(elem_id, id) {
    let elem = document.getElementById(elem_id);
    elem.href = "/?id=" + id;
    elem.onclick = e => {
        e.preventDefault();
        load_id_spa(id);
    }
}

// Get the swf file url from the given ID
function swf_url(id) {
    return "/swf/" + ("00" + id).substr(-2) + ".swf"
}

// Load and play the swf file from the given URL
function load_and_play(url) {
    let abs_url = new URL(url, window.location.href).toString();
    console.log("Loading SWF file " + url);

    fetch(abs_url).then(response => {
        if (response.ok) {
            response.arrayBuffer().then(data => {
                player.play_swf_data(data).then(_ => {
                    if (player.play_button) player.play_button.style.display = "none";
                    player.play_button_clicked(player);
                });
            });
        } else {
            console.error("SWF load failed: " + response.status + " " + response.statusText + " for " + url);
        }
    });
}

// Try to resume the ruffle instance, and update fake-context's resume
function try_resume() {
    context.resume();
    if (player.instance) {
        player.instance.play();
    }
};