import { extend } from '../../utils'
import { createStyle } from '../style'

function setAttribute(this: any, key: string, value: any) {
    if (value) {
        this.node.attrs[key] = value
        extend(true, this, this.node.attrs)
        if (['class', 'className', 'id'].includes(key)) {
            this.setStyle(createStyle(this.node))
        }
    }
    return this
}

function getAttribute(this: any, key?: string) {
    if (typeof key === 'string') {
        return this.node.attrs[key] || this[key]
    } else {
        return this.node.attrs
    }
}

function removeAttribute(this: any, key: string) {
    if (typeof key === 'string') {
        delete this.node.attrs[key]
        delete this[key]
    }
    return this
}

function attr(this: any, key?: string, value?: any) {
    if (value !== undefined) {
        return setAttribute.bind(this)(key, value)
    } else {
        return getAttribute.bind(this)(key)
    }
}

export default { setAttribute, getAttribute, removeAttribute, attr }
