let settingsOpen = false;

let currentLemmaIndex = 0;
if (localStorage.getItem('startdate') != undefined) {
    currentLemmaIndex = Math.floor(new Date().getTime() / 1000 / 60 / 60 / 24) - localStorage.getItem('startdate');
    currentLemmaIndex += parseInt(localStorage.getItem('offset'));
} else {
    localStorage.setItem('startdate', Math.floor(new Date().getTime() / 1000 / 60 / 60 / 24));
    localStorage.setItem('offset', 0);
}




let listOfLemmas = []


function displayResult(parsedJSON) {
    var bestResult = parsedJSON.data[0]
    console.log(bestResult)
    // DOM modifications
    // Resetting divs
    document.getElementById("words").innerHTML = "";
    document.getElementById("senses").innerHTML = "";
    // Writing to those divs
    // Word Container Start
    for (var wordIndex in bestResult.japanese) {
        var wordcontainer = document.createElement("div");
        wordcontainer.className = "word-container";
        wordcontainer.id = "word-container-" + wordIndex;
        // Word div Start
        var worddiv = document.createElement("div");
        worddiv.className = "word";
        if (bestResult.japanese[wordIndex].word != undefined) {
            worddiv.innerHTML = bestResult.japanese[wordIndex].word;
        } else {
            worddiv.innerHTML = currentLemma;
        }

        wordcontainer.appendChild(worddiv);
        // Word div End
        // Reading div Start
        var readingdiv = document.createElement("div");
        readingdiv.className = "reading";
        readingdiv.innerHTML = bestResult.japanese[wordIndex].reading;
        wordcontainer.appendChild(readingdiv);
        // Reading div End
        document.getElementById("words").appendChild(wordcontainer);
    }
    // Word Container End
    // Senses Container Start
    for (var sensesIndex in bestResult.senses) {
        var sensecontainer = document.createElement("div");
        sensecontainer.className = "sense-container";
        sensecontainer.id = "sense-container-" + sensesIndex;
        // Sense Type div Start
        var sensetypediv = document.createElement("div");
        sensetypediv.className = "sense-types";
        sensetypediv.innerHTML = bestResult.senses[sensesIndex].parts_of_speech[0]; // is a list but for some reason there is always only one element
        sensecontainer.appendChild(sensetypediv);
        // Sense Type div End
        // Sense Definitions div Start
        var definitionsdiv = document.createElement("div");
        definitionsdiv.className = "sense-definitions";
        definitionsdiv.innerHTML = bestResult.senses[sensesIndex].english_definitions[0]; // is a list but for some reason there is always only one element
        sensecontainer.appendChild(definitionsdiv);
        // Sense Definitions div End
        // Word Container End
        document.getElementById("senses").appendChild(sensecontainer);
    }
}

// Get information on the currently selected lemma
function updateCurrentLemma() {
    document.getElementById("word-number").innerHTML = currentLemmaIndex + 1;
    currentLemma = listOfLemmas[currentLemmaIndex];
    const url = 'https://ontake.dev/daily-kanji/assets/datasets/building-dataset/jisho-dataset/' + currentLemma;
    $.ajax({
        url: url,
        success: function(result) {
            parsedJSON = JSON.parse(result)
            displayResult(parsedJSON)
        }
    });
}

function updateOffset() {
    localStorage.setItem('offset', currentLemmaIndex - (Math.floor(new Date().getTime() / 1000 / 60 / 60 / 24) - localStorage.getItem('startdate')));
}

// Previous lemma
function previousLemma() {
    currentLemmaIndex--;
    if (currentLemmaIndex < 0) {
        currentLemmaIndex = 0;
    }
    updateOffset()
    updateCurrentLemma();
}

// Next lemma
function nextLemma() {
    currentLemmaIndex++;
    updateOffset()
    updateCurrentLemma();
}

// Update theme
function updateTheme() {
    if (localStorage.getItem('daily-kanji-theme') == undefined) {
        localStorage.setItem('daily-kanji-theme', 0);
    }
    if (localStorage.getItem('daily-kanji-theme') == "0") {
        document.documentElement.style.setProperty('--text-color', "white");
        document.documentElement.style.setProperty('--bg-color-1', "#000000");
        document.documentElement.style.setProperty('--bg-color-2', "#ffffff0f");
        document.documentElement.style.setProperty('--border-color-1', "#ffffff38");
        document.documentElement.style.setProperty('--scrollbar-color-1', "#ffffff");
        document.documentElement.style.setProperty('--scrollbar-color-2', "#393939");
        document.documentElement.style.setProperty('--invert-state', "0");
    } else {
        document.documentElement.style.setProperty('--text-color', "black");
        document.documentElement.style.setProperty('--bg-color-1', "#ffffff");
        document.documentElement.style.setProperty('--bg-color-2', "#0000000f");
        document.documentElement.style.setProperty('--border-color-1', "#00000038");
        document.documentElement.style.setProperty('--scrollbar-color-1', "#000000");
        document.documentElement.style.setProperty('--scrollbar-color-2', "#c7c7c7");
        document.documentElement.style.setProperty('--invert-state', "1");
    }
}

// Theme toggle
function themeToggle() {
    if (localStorage.getItem('daily-kanji-theme') == "0") {
        localStorage.setItem('daily-kanji-theme', 1);
    } else {
        localStorage.setItem('daily-kanji-theme', 0);
    }
    updateTheme();
}

// Update Start Date
function updateStartDate() {
    localStorage.setItem('startdate', document.getElementById("start-date-input").value);
}

// Open Settings
function openSettings() {
    if (!settingsOpen) {
        var settingsDiv = document.createElement("div");
        settingsDiv.id = "settings-container";
        //Start Date
        var startDateLabel = document.createElement("div");
        startDateLabel.id = "start-date-label";
        startDateLabel.innerHTML = "Start Date"
        var startDateInput = document.createElement("input");
        startDateInput.type = "number"
        startDateInput.value = localStorage.getItem('startdate');
        startDateInput.id = "start-date-input";
        startDateInput.oninput = updateStartDate;
        settingsDiv.appendChild(startDateLabel);
        settingsDiv.appendChild(startDateInput);
        //Disclaimer
        var settingsDisclaimerLabel = document.createElement("div");
        settingsDisclaimerLabel.id = "settings-disclaimer-label";
        settingsDisclaimerLabel.innerHTML = "Please note that a refresh of the page is required to show changes.<br><br>Tip: To close this page click on the settings icon again."
        settingsDiv.appendChild(settingsDisclaimerLabel);
        //End
        settingsDiv.id = "settings-container"
        document.body.appendChild(settingsDiv);
        settingsOpen = true;
    } else {
        document.getElementById("settings-container").remove()
        settingsOpen = false;
    }
}

updateTheme();

document.getElementById("current-date").innerHTML = $.format.date(new Date(), 'ddd, MMMM d, yyyy');

// Get list of lemmas
const url = 'https://ontake.dev/daily-kanji/assets/datasets/listoflemmas.txt';
$.ajax({
    url: url,
    success: function(result) {
        listOfLemmas = result.split("\r\n");
        updateCurrentLemma();
    }
});