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

function isNumber(obj) {
    return obj === +obj
}

const createPoint = (value: string | number | { x: number, y: number } | number[], defalutValue: { x: number, y: number }) => {
    const valueType = type(value)
    switch (valueType) {
        case 'number': {
            return { x: value, y: value }
        }
        case 'string': {
            const [x, y = x] = (value as string).split(/(\s|,)/).filter((v) => v.trim() && isNumber(+v))
            return { x: +x, y: +y }
        }
        case 'array': {
            return {
                x: +value[0],
                y: +value[1],
            }
        }
        case 'object': {
            return {
                x:  (value as { x: number, y: number }).x || defalutValue.x,
                y: (value as { x: number, y: number }).y || defalutValue.y,
            }
        }
        default: {
            return defalutValue
        }
    }
}

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)
            }
        })

        if (typeof style.backgroundFrame === 'string') {
            style.backgroundFrame = style.backgroundFrame.split(/\s/).map((n: string) => +n)
        }

        if (style.anchor) style.anchor = createPoint(style.anchor, { x: .5, y: .5 })
        if (style.scale) style.scale = createPoint(style.scale, { x: 1, y: 1})
    })

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