const CANVAS = document.getElementById("ui-canvas")
const UI_CUTTER = new Image(CANVAS)
const FORM = document.getElementById("cutter-form")

async function updateFromForm(){
    let data = new FormData(FORM)

    let image = data.get("image")
    if(image.size > 0){
        if(UI_CUTTER.currentImageFile != image){
            await UI_CUTTER.setImage(image)
            UI_CUTTER.clearGlitch()
        }
    } else {
        UI_CUTTER.clearImage()
    }

    document.getElementById("welcome-panel").hidden = image.size > 0
    document.getElementById("glitch-panel").hidden = image.size == 0

    UI_CUTTER.render()
}

FORM.addEventListener("submit", e => {
        e.preventDefault()
        updateFromForm()
    })

FORM.addEventListener("reset", e => {
        FORM.elements["image"].value = ""
        updateFromForm()
    })

document.getElementById("download-btn").addEventListener("click", async e => {
    e.preventDefault();
    let data = await UI_CUTTER.toBlob("image/jpeg", 1);
    let a = document.createElement('a')
    a.href = URL.createObjectURL(data)
    a.download = UI_CUTTER.currentImageFile.name
    a.click()
    setTimeout(() => URL.revokeObjectURL(a.href), 10000)
})
