import * as PIXI from 'pixi.js'
import { getValue, getCoverRect } from 'lib/utils'

export function backgroundColor(co: any) {
    co.on('update', ({ instance, style }) => {
        if (
            instance.layout.newStyle &&
            !instance.layout.newStyle.backgroundColor
        ) return
        if (
            getValue(style, 'backgroundColor') && 
            (['sprite', 'animatedsprite'].includes(instance.type))
        ) {
            const coverRect = getCoverRect(instance)
            if (coverRect) {
                const { x, y, width, height } = coverRect
                const draw = (bg: any) => {
                    bg.beginFill(style.backgroundColor)
                    bg.drawRect(x, y, width, height)
                    bg.endFill()
                }

                if (instance._background) {
                    instance._background.clear()
                    draw(instance._background)
                } else {
                    const bg = new PIXI.Graphics()
                    bg.name = 'background-color'
                    draw(bg)
                    instance.addChildAt(bg, 0)
                    instance._background = bg
                }
            }
        }
    })
}
