'use strict'

modules['blur'] = {
    config: [
        ['passes', 'int', '1'],
    ],

    render: async (time, self, config) => {
        const {
            passes,
        } = { ...config }

        let bufferAId = getOutputBufferId()
        let bufferBId = lockBuffer()
        const blurDivisor = 1 / 5
        for (let i = 0; i < passes; ++i) {
            const src = greyscaleBuffers[bufferAId]
            const dst = greyscaleBuffers[bufferBId]
            let p = 0

            for (let x = 0; x < 640; ++x) {
                dst[p] = src[p++]
            }

            if (i & 0) {
                for (let y = 1; y < 480-1; ++y) {
                    dst[p] = src[p++]
                    for (let x = 1; x < 640-1; ++x) {
                        const v = src[p - 641] +
                                //src[p - 640] +
                                src[p - 639] +
                                //src[p - 1] +
                                src[p] +
                                //src[p + 1] +
                                src[p + 639] +
                                //src[p + 640] +
                                src[p + 641]
                        dst[p++] = v * blurDivisor
                    }
                    dst[p] = src[p++]
                }
            } else {
                for (let y = 1; y < 480-1; ++y) {
                    dst[p] = src[p++]
                    for (let x = 1; x < 640-1; ++x) {
                        const v = //src[p - 641] +
                                src[p - 640] +
                                //src[p - 639] +
                                src[p - 1] +
                                src[p] +
                                src[p + 1] +
                                //src[p + 639] +
                                src[p + 640]
                                //src[p + 641]
                        dst[p++] = v * blurDivisor
                    }
                    dst[p] = src[p++]
                }
            }


            for (let x = 0; x < 640; ++x) {
                dst[p] = src[p++]
            }

            const swap = bufferBId
            bufferBId = bufferAId
            bufferAId = swap
        }
        setOutputBufferId(bufferAId)
        unlockBuffer(bufferBId)
    }
}
