const camelize = (str) => (str + "").replace(/[_|-]\D/g, (match) => match.charAt(1).toUpperCase())
const forin = (object: object, fn: (key?: string, value?: any) => void) => {
    if (typeof object === 'object') {
        for (const key in object) {
            if (object.hasOwnProperty(key)) {
                const value = object[key]
                fn(key, value)
            }
        }
    }
}
const replaceValue = (value: string, extra = {}) => {
    if (value.includes('data.')) {
        const datakey = value.split('data.')[1].trim()
        return extra[datakey]
    } else {
        return value
    }
}

export const styleHandler = {
    parse(styleString: string) {
        const params = {}
        if (styleString && typeof styleString === 'string') {
            let str = styleString.trim().split(/;|,/)
            for (let i = 0, n = str.length; i < n; i++) {
                if (str[i]) {
                    const param = str[i].split(/:|=/)
                    params[param[0].trim()] = param[1].replace(/'|"/g, '').trim()
                }
            }
        }
        return params
    },
    camelizify(style) {
        forin(style, (key: string, value: any) => {
            if (key.includes('_') || key.includes('-')) {
                Object.defineProperty(style, camelize(key), {
                    value,
                    enumerable: true,
                    writable: true,
                })
                delete style.key
            }
        })
        return style
    },
    replaceValue,
    dataify(style, extra) {
        forin(style, (key: string, value: any) => {
            style[key] = replaceValue(value, extra)
        })
        return style
    },
}
