
window.onload = async function (ev) {
    let data_req = await fetch("/index.json")
    let data = await data_req.json()
    let fuse = new Fuse(data, {keys: [
            "tags",
            "id",
            "title",
            "body"
        ]
    })
    async function search(args) {
        try {
            let x = fuse.search(args)
            return x
        } catch  {
            return null
        }
    }
    document.getElementById('searchbox').addEventListener("input",
        async function(e) {
            let results = document.getElementById('results') // .innerHTML = idx.search(e.target.value))
            if (e.target.value == "") {
                results.innerHTML = ""
            } else {
                Promise.race([
                    search(e.target.value),
                    new Promise((resolve, reject) => {
                        setTimeout(() => {
                            resolve(-1)
                        }, 3000);
                    })
                ]).then((r) => {
                    if (r == null) {
                        results.innerHTML = "<ul class='sresult'><li class='sresult'><strong>Search results</strong></li><li class='sresult'>An error occured</li></ul>"
                    } else if (r == -1) {
                        results.innerHTML = "<ul class='sresult'><li class='sresult'><strong>Search results</strong></li><li class='sresult'>Query timed out</li></ul>"
                    } else if (r.length == 0) {
                        results.innerHTML = "<ul class='sresult'><li class='sresult'><strong>Search results</strong></li><li class='sresult'>No result</li></ul>"
                    } else {
                        results.innerHTML =  "<ul class='sresult'>" + r.map((it) => "<li class='sresult'>" + "<a href=\"/" + it.item.id + ".html\">" + it.item.title + "</a></li>").reduce((a, b) => a + b) + "</ul>"
                    }
                })
            }
        }
    )
}
