<template>
    <button :title="ariaLabel"
            type="button"
            :aria-label="ariaLabel || label" :aria-description="ariaDescription"
            @click="toggle" :class="buttonClass">
        <slot name="default" :active="active">
            <span class="icon">
                <i :class="icon"></i>
            </span>
            <label v-if="label">{{ label }}</label>
        </slot>
    </button>
</template>
<script>
export default {
    props: {
        initialActive: {type: Boolean, default: null},
        el: {type: String, default: ""},
        label: {type: String, default: ""},
        icon: {type: String, default: "fa fa-bars"},
        ariaLabel: {type: String, default: ""},
        ariaDescription: {type: String, default: ""},
        activeClass: {type: String, default:"active"},
        /// switch toggle of all items of this group.
        group: {type: String, default: ""},
    },

    data() {
        return {
            active: this.initialActive,
        }
    },

    computed: {
        groupClass() {
            return this.group && "a-switch-" + this.group || ''
        },

        buttonClass() {
            return [
                this.active && 'active' || '',
                this.groupClass
            ]
        }
    },

    methods: {
        toggle() {
            this.set(!this.active)
        },

        set(active) {
            if(this.el) {
                const el = document.querySelector(this.el)
                if(active)
                    el.classList.add(this.activeClass)
                else
                    el.classList.remove(this.activeClass)
            }
            this.active = active
            if(active)
                this.resetGroup()
        },

        resetGroup() {
            if(!this.groupClass)
                return
            const els = document.querySelectorAll("." + this.groupClass)
            for(var el of els)
                if(el != this.$el)
                    el.__vnode.ctx.ctx.set(false)
        },
    },

    mounted() {
        if(this.initialActive !== null)
            this.set(this.initialActive)
    },
}
</script>
