'use strict'

// mode ref => https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
modules['overlay'] = {
    config: [
        ['alpha', 'float', 1],
        ['position', 'float2', [0, 0]],
        ['source', 'string', ''],
        ['mode', 'string', 'source-over'],
        ['scale', 'float', 1.0],
        ['width', 'int', 640],
        ['height', 'int', 480],
    ],

    render: async (time, self, config) => {
        const {
            alpha,
            position,
            source,
            mode,
            scale,
            width,
            height,
        } = { ...config }

        if (source && alpha > 0) {
            const destWidth = Math.floor(width * scale)
            const destHeight = Math.floor(height * scale)
            const posX = position[0] - Math.floor((destWidth - width) / 2)
            const posY = position[1] - Math.floor((destHeight - height) / 2)
    
            ctx.globalAlpha = alpha
            ctx.globalCompositeOperation = mode
            ctx.drawImage(overlays[source], posX, posY, destWidth, destHeight)
        }
    }
}