const loading_message = "results are loading...";
const kinda_long = "results are still loading...";
const elapsed_message = "time elapsed";

let time_elapsed = 0.0;
let timer_interval;

function updateTimer() {
    if (document.getElementById("stopwatch") !== null) {
        const timer_element = document.getElementById("stopwatch")
        time_elapsed += 1 / 100;
        timer_element.innerHTML = time_elapsed.toString();
        if (time_elapsed > 5) {
            const notice1 = document.getElementById("loading_message");
            notice1.innerHTML = kinda_long;
        }
    }
}

function startLoading() {
    if (document.getElementById("loading") === null) {
        const results_area = document.getElementById("results-area");
        const loading_element = document.createElement("div");
        loading_element.id = "loading";

        const notice1 = document.createElement("span");
        notice1.id = "loading_message";
        notice1.innerHTML = loading_message;
        loading_element.appendChild(notice1);

        const timer_notice = document.createElement("span");
        timer_notice.id = "timer_message";
        timer_notice.innerHTML = elapsed_message;

        const timer_element = document.createElement("div");
        timer_element.id = "stopwatch";
        loading_element.appendChild(timer_element);
        results_area.appendChild(loading_element);
        timer_interval = setInterval(updateTimer, 10);
    }
}

function stopLoading() {
    if (document.getElementById("loading") !== null) {
        clearInterval(timer_interval);

        const results_area = document.getElementById("results-area");
        const loading_element = document.getElementById("loading");
        results_area.removeChild(loading_element);
    }
}

startLoading();

function process(result) {
    stopLoading();
    const json = result; //JSON.parse(result);
    if (json.hasOwnProperty( "error") || !json.hasOwnProperty( "results")) {
        const response_element = document.getElementsByClassName("response")[0];
        const results_area = document.getElementById("results-area");
        response_element.removeChild(results_area);

        const error_element = document.createElement("div");
        error_element.classList.add("error");
        if (json.hasOwnProperty( "error")) {
            error_element.innerText = json.error;
        } else {
            error_element.innerText = "unknown serverside error occurred! please try your request again, and contact an administrator if the error persists!";
        }
        response_element.appendChild(error_element);
    } else {
        const search_results = json.results;
        const response_element = document.getElementsByClassName("response")[0];
        const search_result_list = document.createElement("ol");
        const results_area = document.getElementById("results-area");
        const stats_element = document.createElement("div");
        stats_element.classList.add("stats");
        stats_element.innerText = `found ${search_results.search_results.length} results in ${search_results.query_time} seconds (${search_results.page_rank_time} was pageranking)`;
        results_area.appendChild(stats_element);

        if (search_results.hasOwnProperty( "note")) {
            const note_element = document.createElement("div");
            note_element.classList.add("note");
            note_element.innerText = search_results.note;
            results_area.insertBefore(note_element, stats_element);
        }

        search_result_list.classList.add("search-result-list");

        for (const result_obj of search_results.search_results) {
            const li = document.createElement("li");
            const a = document.createElement("a");
            a.classList.add("search-result");
            a.href = result_obj.url;
            const h2 = document.createElement("h2");
            h2.classList.add("search-title");
            if (result_obj.hasOwnProperty( "title")) {
                h2.innerText = result_obj.title;
            } else {
                h2.innerText = result_obj.url;
            }
            a.appendChild(h2);
            const resultstat = document.createElement("span");
            resultstat.classList.add("resultstat");
            if (result_obj.hasOwnProperty( "title")) {
                const search_url = document.createElement("span");
                search_url.classList.add("search-url");
                search_url.innerText = result_obj.url + " ";
                resultstat.appendChild(search_url);
            }
            const relevance = document.createElement("span");
            relevance.classList.add("search-relevance");
            relevance.innerText = `(${result_obj.percentage}%, ${result_obj.value} / ${search_results.max_relevance})`;
            const enginelist = document.createElement("span");
            enginelist.classList.add("enginelist");
            if (result_obj.hasOwnProperty("asklyphe")) {
                if (result_obj.asklyphe === true) {
                    const tinylyphe = document.createElement("img");
                    tinylyphe.src = "/static/img/tinylyphe.png";
                    tinylyphe.title = "from askLyphe database";
                    enginelist.appendChild(tinylyphe);
                }
            }
            if (result_obj.hasOwnProperty("bing")) {
                if (result_obj.bing === true) {
                    const tinybutterfly = document.createElement("img");
                    tinybutterfly.src = "/static/img/tinybutterfly.png";
                    tinybutterfly.title = "from external search engine";
                    enginelist.appendChild(tinybutterfly);
                }
            }
            if (result_obj.hasOwnProperty("google")) {
                if (result_obj.google === true) {
                    const tinyletter = document.createElement("img");
                    tinyletter.src = "/static/img/tinyletter.png";
                    tinyletter.title = "from external search engine";
                    enginelist.appendChild(tinyletter);
                }
            }
            resultstat.appendChild(relevance);
            resultstat.appendChild(enginelist);
            a.appendChild(resultstat);
            if (result_obj.hasOwnProperty( "description")) {
                const desc = document.createElement("span");
                desc.classList.add("search-description");
                desc.innerText = result_obj.description;
                a.appendChild(desc);
            }
            li.appendChild(a);
            search_result_list.appendChild(li);
        }

        results_area.appendChild(search_result_list);

        if (search_results.blocked.length > 0) {
            const blocked_header = document.createElement("span");
            blocked_header.classList.add("blocked-header");
            blocked_header.innerText = `${search_results.blocked.length} results were pruned from search results for the following reasons:`;
            results_area.appendChild(blocked_header);
            const blocked_results = document.createElement("ol");
            blocked_results.classList.add("blocked-results");
            for (const blocked of search_results.blocked) {
                const li = document.createElement("li");
                li.innerText = `"${blocked.url}" because "${blocked.reason}"`;
                blocked_results.appendChild(li);
            }
            results_area.appendChild(blocked_results);
        }
    }
}

let xml_http = new XMLHttpRequest();

xml_http.onload = (e) => {
    process(xml_http.response);
}

let query = "Deez";
let engines = "";
let params = (new URL(document.location)).searchParams;
if (params.has("q")) {
    query = params.get("q");
}
if (params.has("engines")) {
    engines = `&engines=${params.get("engines")}`;
}

xml_http.open("GET", `${window.location.origin}/ask_json?q=${encodeURIComponent(query)}${engines}`);
xml_http.responseType = "json";
xml_http.send();