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

export function overflow(co: any) {
    co.on('update', ({ instance, style }) => {
        const layout = instance.layout
        if (!layout || !layout.styleHasChanged('overflow')) return
        const { borderRadius = 0, overflow } = style
        const coverRect = getCoverRect(instance)
        if (overflow && coverRect) {
            const { width } = instance.getGlobalBounds()
            const _borderRadius = instance.layout.transform.length(width, borderRadius)
            const { x: coverX, y: coverY, width: coverWidth, height: coverHeight } = coverRect
            
            if (instance.mask && instance.mask.name === 'overflow') {
                instance.mask.destroy()
                instance.mask = null
            }
            if (!(_borderRadius && _borderRadius > 0)) {
                // 设置 mask
                const mask = new PIXI.Graphics()
                mask.beginFill()
                if (_borderRadius >= width / 2) {
                    mask.drawCircle(0, 0, coverWidth / 2)
                } else {
                    mask.drawRoundedRect(coverX, coverY, coverWidth, coverHeight, _borderRadius)
                }
                mask.endFill()
                mask.name = 'overflow'
                instance.addChildAt(mask, 0)
                instance.mask = mask
            }
        }
    })
}
