import { Namespace } from "../../utils/namespace";
import { Color } from "../../utils/color";

const namespace = Namespace.Create('badge')

export default {
    name: namespace.name,
    props:{
        tag:{
            type: String,
            default:'div'
        },
        theme:{
            type: String,
            default: 'red'
        },
        dot:{
            type: Boolean,
            default: false
        },
        max:{
            type: Number
        },
        content:{
            type: Number | String
        },
        color:{
            type:String
        },
        offset:{
            type:Array
        },
        small:{
            type: Boolean,
            default: false
        }
    },
    computed:{
        cls(){
            return namespace.derive([
                this.theme,
                {
                    dot: this.dot,
                    fixed: !!this.$slots.default,
                    small: this.small
                }
            ])
        },
        wrapperCls(){
            return namespace.derive('wrapper')
        },
        style(){
            const style = {}
            if(this.color){
                style.backgroundColor = this.color
                const clr = Color.FromHex(this.color)
                style.color = clr.isDark ? Color.WHITE : Color.BLACK
            }
            if(this.offset){
                const [x,y] = this.offset
                if(this.$slots.default){
                    style.top = `${y}px`
                    style.right = `${-x}px`
                }else{
                    style.marginLeft = `${x}px`
                    style.marginTop =  `${y}px`
                }
            }
            return style
        },
        hasContent(){
            return this.$slots.content || !!this.content
        }
    },
    render(){
        const renderContent = ()=> {
            if(this.dot){
                return
            }

            if(this.$slots.content){
                return this.$slots.content
            }

            const {max, content} = this.$props

            if(max && !Number.isNaN(Number(content))  && content> max){
                return `${max}+`
            }

            return this.content
        }

        const renderBadge = ()=> {
            if(this.hasContent || this.dot){
                return (
                   <div class={this.cls} style={this.style}>
                       {renderContent()}
                   </div> 
                )
            }
        }

        if(this.$slots.default){
            const tag = this.tag
            return (
                <tag class={this.wrapperCls}>
                    {this.$slots.default}
                    {renderBadge()}
                </tag>
            )
        }

        return renderBadge()
    }
}