function main() {
    refreshStatus();
    setInterval(refreshStatus, 10000)
}

function refreshStatus() {
    return fetch("/api/v1/status")
        .then(res => res.json())
        .then(res => {
            const newStatus = document.createElement("tr")
            newStatus.id = "status"

            let td = document.createElement("td")
            td.innerText = res.data.status
            newStatus.appendChild(td)

            td = document.createElement("td")
            td.innerText = res.data.title
            newStatus.appendChild(td)

            td = document.createElement("td")
            td.innerText = res.data.url
            document.getElementById("url-input").placeholder = res.data.url
            newStatus.appendChild(td)

            document.getElementById("status").replaceWith(newStatus)
        })
        .catch(err => {
            console.error(err);
            window.location.reload()
        })
}

function castUrl() {
    const urlInput = document.getElementById("url-input")
    const url = urlInput.value
    if (url === "") return Promise.resolve()
    return fetch("/api/v1/cast", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            "url": url,
        })
    })
    .then(res => res.json())
    .then(() => refreshStatus())
    .then(() => {
        urlInput.value = ""
    })
}

function reset() {
    const urlInput = document.getElementById("url-input")
    return fetch("/api/v1/cast", {
        method: "DELETE",
    })
    .then(res => res.json())
    .then(() => refreshStatus())
    .then(() => {
        urlInput.value = ""
    })
}

main()