import { Glitcher } from "./lib/glitcher";

const CANVAS = document.getElementById("ui-canvas")
const UI_GLITCHER = new Glitcher(CANVAS)
const FORM = document.getElementById("glitcher-form")

async function updateFromForm(){
    let data = new FormData(FORM)
    
    let image = data.get("image")
    if(image.size > 0){
        if(UI_GLITCHER.currentImageFile != image){
            await UI_GLITCHER.setImage(image)
            UI_GLITCHER.clearGlitch()
        }
    } else {
        UI_GLITCHER.clearImage()
    }

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

for(let el of FORM.elements){
    el.addEventListener("change", () => FORM.requestSubmit())
}

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_GLITCHER.toBlob("image/jpeg", 0.9);
    let a = document.createElement('a')
    a.href = URL.createObjectURL(data)
    a.download = UI_GLITCHER.currentImageFile.name
    a.click()
    setTimeout(() => URL.revokeObjectURL(a.href), 10000)
})

CANVAS.addEventListener("pointerdown", e => {
    let pointerId = e.pointerId;

    let lastX = undefined;
    let lastY = undefined;
    let lastCommit = null;

    function applyGlitch(e){
        if(e.pointerId != pointerId){
            return
        }

        let canvasRect = CANVAS.getBoundingClientRect()
        let x = e.clientX - canvasRect.left
        let y = e.clientY - canvasRect.top

        let now = Date.now()

        if(lastCommit === null || now - lastCommit > 100){
            let width = 50;
            if(e.pointerType == "touch"){
                width *= 2
            }
            
            let deltaX = lastX !== undefined ? x - lastX : 0
            let deltaY = lastY !== undefined ? y - lastY : 0

            width += Math.max(Math.abs(deltaX), Math.abs(deltaY))
            width += Math.random()*2

            UI_GLITCHER.addGlitch(x, y, width)
            UI_GLITCHER.render()

            lastCommit = now
        }

        lastX = x
        lastY = y
    }

    function endGlitch(e){
        if(e.pointerId != pointerId){
            return
        }

        window.removeEventListener("pointermove", applyGlitch)
        window.removeEventListener("pointerup", endGlitch)
    }

    window.addEventListener("pointerup", endGlitch)
    window.addEventListener("pointermove", applyGlitch)

    applyGlitch(e)
})

/*function startRendering(){
    UI_GLITCHER.render()
    requestAnimationFrame(startRendering)
}
startRendering()*/

setInterval(() => UI_GLITCHER.render(), 500)
updateFromForm()