'use strict'

modules['depthFilter'] = {
    config: [
        ['edgeValue', 'float', 0.1],
        ['stripeSize', 'int', 0],
        ['stripeBrightness', 'float', 0.5],
        ['nonStripeBrightness', 'float', 1.0],
        ['decaySpeed', 'float', 0.1],
    ],

    render: async (time, self, config) => {
        const {
            edgeValue,
            stripeSize,
            stripeBrightness,
            nonStripeBrightness,
            decaySpeed,
        } = { ...config }

        const dstBufferId = lockBuffer()
        const srcBufferId = getOutputBufferId()
        const srcBuffer = greyscaleBuffers[srcBufferId]
        const dstBuffer = greyscaleBuffers[dstBufferId]

        for (let x = 0; x < 640; ++x) {
            let bufferIndex = x
            let currentValue = edgeValue
            let stripeHeight = 0
            let stripeOn = true
            for (let y = 0; y < 480; ++y) {
                const newValue = srcBuffer[bufferIndex]
                let thisValue
                if (newValue > currentValue) {
                    thisValue = currentValue = newValue
                    stripeHeight = 0
                    stripeOn = true
                } else if (currentValue > 0) {
                    currentValue = Math.max(currentValue - decaySpeed, 0)
                    if (stripeHeight >= stripeSize) {
                        stripeOn = !stripeOn
                        stripeHeight = 0
                    } else {
                        stripeHeight++
                    }
                    if (stripeOn) {
                        thisValue = currentValue * nonStripeBrightness
                    } else {
                        thisValue = currentValue * stripeBrightness
                    }
                }
                dstBuffer[bufferIndex] = thisValue
                bufferIndex += 640
            }
        }

        setOutputBufferId(dstBufferId)
        unlockBuffer(srcBufferId)
    }
}
