var currentTheme = localStorage.getItem("theme");

console.log("loaded " + JSON.stringify(currentTheme));

var toggle = document.getElementById("theme-toggle");
var html = document.getElementsByTagName("html");
var body = document.body;
var divs = document.getElementsByTagName("div");
var links = document.getElementsByTagName("a");

let checkTheme = () =>
{
    console.log(JSON.stringify(currentTheme));
    // check for previously set theme
    if (JSON.stringify(currentTheme) == "\"dark\"") 
    {
        console.log("toggling");
        toggleTheme();
    } 
}


let theme = "";

toggle.addEventListener("click", (e) =>
{
    e.preventDefault();
    toggleTheme();
});

let toggleTheme = () =>
{
    // toggle classes on elements
    for(let i = 0; i < html.length; i++)
    {
        html[i].classList.toggle("dark-mode");
    }

    body.classList.toggle("dark-mode");
    
    for(let i = 0; i < divs.length; i++)
    {
        divs[i].classList.toggle("dark-mode");
    }    
    for(let i = 0; i < links.length; i++)
    {
        links[i].classList.toggle("dark-mode");
    }

    // check toggle state and save
    if(body.classList.contains("dark-mode"))
    {
        console.log("setting dark mode...");
        theme = "dark";
    } else {
        console.log("setting light mode...");
        theme = "light";
    }

    console.log("saving " + JSON.stringify(theme));
    localStorage.setItem('theme', theme);
}
