const HISTORY_KEY = "biermann.history";
const HISTORY_PORTLET = "biermann.historyportlet";
const NAME_SUFFIX = " — Institut für Physik";


// Removes duplicate entries from an array
function dedupeArray(array) {
    let map = {};
    var deduped = [];

    array.forEach(entry => {
        let stringified = JSON.stringify(entry);
        if (!map.hasOwnProperty(stringified)) {
            map[stringified] = null;
            deduped.push(entry);
        }
    });
    return deduped;
}


class History {
    constructor(entries) {
        this.entries = entries;
    }

    static load() {
        try {
            // Get history
            let entries = JSON.parse(localStorage.getItem(HISTORY_KEY));
            
            // Validate history
            if (!(entries instanceof Array)) throw "History is not an array";
            entries.forEach(entry => {
                if (!(entry.hasOwnProperty("name") && entry.hasOwnProperty("url"))) throw "Invalid entries in history";
            });

            return new History(entries)
        } catch (error) {
            console.log("No valid history in local storage (" + error + ")");
            return new History([]);
        }
    }
    store() {
        try {
            localStorage.setItem(HISTORY_KEY, JSON.stringify(this.entries));
        } catch (error) {
            console.log("Failed to save history in local storage (" + error + ")");
        }
    }

    add(name, url) {
        // Add element to history, remove duplicates and trim it to contain only 5 elements
        this.entries.unshift({ name: name, url: url });
        this.entries = dedupeArray(this.entries);
        while (this.entries.length > 5) this.entries.pop();
    }

    asHTML(filterURL, trimSuffix) {
        // Remove `filterURL` from entries
        let entries = this.entries.filter(entry => entry.url != filterURL);
        let html = entries.reduce((html, entry) => {
            // Remove `trimSuffix` from name if necessary
            let name = entry.name.endsWith(trimSuffix) ? entry.name.substr(0, entry.name.length - trimSuffix.length) : entry.name;
            return html + "<p><a href=\"" + entry.url + "\">" + name + "</a></p>\n";
        }, "");
        return html.length ? html : "Sie haben bisher keine andere Seite besucht oder JavaScript deaktiviert";
    }
}


window.onload = () => {
    // Load history
    let history = History.load();

    // Capture current title and URL
    let name = window.document.title;
    let url = window.location.pathname;

    // Add site to history and save it
    history.add(name, url);
    history.store();

    // Load and display
    document.getElementById(HISTORY_PORTLET).innerHTML = history.asHTML(url, NAME_SUFFIX);
};