
function log(s) {
    console.log(s)
}

let numErrs = 0

let tm = undefined

function startReload() {
    tm = setInterval(check, 500)
}
startReload()

function stopReload() {
    clearInterval(tm)
    tm = undefined
}

function checkUrl(url, ts, setTs, onChange) {
    // log("checkUrl: " + url + " ts: " + ts)
    const r = new XMLHttpRequest()
    // r.setRequestHeader("xd", "true")
    r.open("HEAD", url)
    r.send()
    r.onload = ()=>{
        // log("ok")
        numErrs = 0
        // let t = r.responseText
        let t = r.getResponseHeader('Last-Modified')
        if(!ts){
            setTs(t)
        }else if(ts!==t){
            onChange(t)
        }
    }
    r.onerror = ()=>{
        // log("err")
        if(++numErrs===10){
            log("stop checks")
            stopReload()
        }
    }
}

function reloadCss(url) {
    log("reloadCss: " + url)
    const link = document.querySelector('link[href*="win.css"]');
    link.href = url + '?v=' + Date.now();
}

let serverTime = undefined
let cssTime = undefined
function check() {
    checkUrl("/debug/start_time", serverTime, t => serverTime = t, ()=>{
        log("reload web")
        stopReload()
        winSaveTimer = null
                // window.location = window.location.href
        location.reload()
    })
    const cssUrl = "win.css"
    checkUrl(cssUrl, cssTime, t => cssTime = t, t=>{
        cssTime = t
        reloadCss(cssUrl)
    })
}

check()

function toggleReload(){
    if(tm) stopReload()
    else startReload()
}
