import AAnimation from '/js/libs/js-AAnimation.js'
export default class ATab extends window.AObject {
    constructor(tabs, content, type = true) {
        super();
        this.selTab = null;
        this.lockTabs = Array.from([]);
        this.tabContents = content;
        this.setAnimation("Slide");
        this.ctabs = Array.from(this.tabContents.children);
        this.aAnimation = new AAnimation();
        this.aAnimation.setType(this.typeAnimation, { "parent": this.tabContents });
        this.type = type;
        if (type) {
            this.tabs = tabs.querySelectorAll(".item");
            this.tabs.forEach((e, i) => {
                if (e.classList.contains("active")) {
                    //   this.ctabs[i].classList.add("show");
                    this.selectedTab(i);
                }

                this.ctabs[i].classList.add("fade");
                e.addEventListener("click", this.eventTabClick.bind(this, e, i));
            });

        } else {
            this.selectedTab(0); 
            this.ctabs.forEach((el) => { el.classList.add("fade"); });
        }
    }
    setAnimation(type) {
        this.typeAnimation = type;
    }
    eventTabClick(e, num) {
        if (e.hasAttribute("disabled") || e.classList.contains("active")) {
            return;
        }
        this.selectedTab(num);
    }
    selectedTab(id) {
        if (this.selTab != null) {
            if (this.lockTabs.length > 0) {
                if (this.lockTabs.includes(this.selTab)){
                    this.disableTab(this.selTab);
                }
            }
            if (this.type) this.tabs[this.selTab].classList.remove("active");
            this.aAnimation.element = this.ctabs[this.selTab];
          
            this.aAnimation.once("endAnimation", (( ev) => { this.setTab(id); }).bind(this));
            this.aAnimation.animation();
        } else {
            this.setTab(id);
        }
    }
    setTab(id) {
        this.aAnimation.element = this.ctabs[id];
        this.aAnimation.animation();
        this.aAnimation.once("endAnimation", ((ev) => { this.trigger("changed", { "tabIndex": id }) }).bind(this));
        if (this.type)  this.tabs[id].classList.add("active");
        this.selTab = id;
    }
    enableTab(id) {
        this.tabs[id].removeAttribute("disabled");
    }
    disableTab(id) {
        this.tabs[id].setAttribute("disabled", "");
    }
}