'use strict'

modules['zoom'] = {
    config: [
        ['repeats', 'int', 5],
        ['zoom', 'float', 1.1],
        ['blend', 'float', 0.25],
        ['offset', 'float2', [0, 0]],
    ],

    render: async (time, self, config) => {
        const {
            repeats,
            zoom,
            blend,
            offset,
        } = { ...config }

        const ox = -offset[0] * 320 + 320
        const oy = offset[1] * 240 + 240

        let bufferAId = getOutputBufferId()
        let bufferBId = lockBuffer()
        const scale = 1 / zoom
        for (let i = 0; i < repeats; ++i) {
            setOutputBufferId(bufferBId)

            const srcBuffer = greyscaleBuffers[bufferAId]
            const dstBuffer = greyscaleBuffers[bufferBId]
            let index = 0
            for (let y = 0; y < 480; ++y) {
                const sy = Math.floor(((y - 240) * scale + oy))
                //if (sy >= 0 && sy < 480) {
                    const sym = sy * 640
                    for (let x = 0; x < 640; ++x) {
                        const sx = Math.floor((x - 320) * scale + ox)
                        //if (sx >= 0 && sx < 640) {
                            dstBuffer[index] = srcBuffer[index] + srcBuffer[sx + sym] * blend
                            index++
                        //} else {
                        //    dstBuffer[index++] = borderColour
                        //}
                    }
                //} else {
                //    for (let x = 0; x < 640; ++x) {
                //        dstBuffer[index++] = borderColour
                //    }
                //}
            }
        
            const swap = bufferBId
            bufferBId = bufferAId
            bufferAId = swap
        }
        setOutputBufferId(bufferAId)
        unlockBuffer(bufferBId)
    }
}
