import toHex from 'colornames'
import { utils } from 'pixi.js'
import { getValue, setValue } from '../../utils'

export function styleHandler(co: any) {
    co.on('beforeCreated beforeUpdate', (style) => {
        if (typeof style !== 'object') return
        // handle colorname
        const attrs = ['backgroundColor', 'borderColor', 'text.color', 'text.fill']
        attrs.map((key: string) => {
            const v = getValue(style, key)
            if (typeof v === 'string') {
                const colorHex = utils.string2hex((v.includes('#') || v.startsWith('0x')) ? v : toHex.get(v).value)
                colorHex && setValue(style, key, colorHex)
            }
        })
    })

    co.on('beforeCreated', (style) => {
        // handle debug
        if (co.debug && !style['borderWidth']) {
           style['borderWidth'] = '1px'
       }
   })

}
