import { __decorate, __metadata } from "tslib";
import { Host, h } from "@stencil/core";
import { areArraysEqual } from "../../utils/array";
import { BEM } from "../../utils/bem";
import { ListenToBreakpoints, balBreakpoints } from "../../utils/breakpoints";
import { stopEventBubbling } from "../../utils/form-input";
import { debounceEvent } from "../../utils/helpers";
import { Logger } from "../../utils/log";
import { ListenToMutation } from "../../utils/mutation";
import { newBalStepOption } from "./bal-step.util";
import { StepButton } from "./components/step-button";
export class Steps {
    constructor() {
        this.stepsId = `bal-steps-${StepsIds++}`;
        this.store = [];
        this.isMobile = balBreakpoints.isMobile;
        /**
         * PUBLIC PROPERTY API
         * ------------------------------------------------------
         */
        /**
         * Steps can be passed as a property or through HTML markup.
         */
        this.options = [];
        /**
         * If `true` the tabs or steps can be clicked.
         */
        this.clickable = true;
        /**
         * Defines the color of the steps so it can be placed on colored backgrounds
         */
        this.color = 'primary';
        /**
         * Set the amount of time, in milliseconds, to wait to trigger the `balChange` event after each keystroke. This also impacts form bindings such as `ngModel` or `v-model`.
         */
        this.debounce = 0;
        /**
         * Value of the current active step
         */
        this.value = undefined;
        /**
         * LISTENERS
         * ------------------------------------------------------
         */
        this.mutationObserverActive = true;
        this.getStepOptions = () => {
            if (this.options.length > 0) {
                return [...this.options.map(newBalStepOption)];
            }
            else {
                return Promise.all(this.items.map(value => value.getOptions()));
            }
        };
        this.updateStore = (newStore) => {
            if (!areArraysEqual(this.store, newStore)) {
                this.store = newStore;
            }
        };
        this.setActiveItem = () => {
            const activeTabs = this.store.filter(t => t.active);
            if (activeTabs.length > 0) {
                const firstActiveTab = activeTabs[0];
                this.value = firstActiveTab.value;
            }
            else {
                if (this.value === undefined && this.store.length > 0) {
                    const firstStep = this.store[0];
                    this.value = firstStep.value;
                }
            }
        };
        this.setActiveContent = () => {
            if (this.options.length === 0) {
                this.items.forEach(item => item.setActive(this.isActive(item)));
            }
        };
        /**
         * EVENT BINDING
         * ------------------------------------------------------
         */
        this.onOptionChange = async () => {
            try {
                const options = await this.getStepOptions();
                this.updateStore(options);
                this.setActiveItem();
                this.setActiveContent();
            }
            catch (e) {
                console.warn('[WARN] - Could not read tab options');
            }
        };
        this.onSelectTab = async (ev, step) => {
            if (step.prevent || step.disabled || !this.clickable) {
                stopEventBubbling(ev);
            }
            if (!step.disabled) {
                if (step.navigate) {
                    step.navigate.emit(ev);
                }
                if (this.clickable) {
                    if (step.value !== this.value) {
                        this.balChange.emit(step.value);
                        await this.select(step);
                    }
                }
            }
        };
    }
    createLogger(log) {
        this.log = log;
    }
    async optionChanged() {
        this.onOptionChange();
        if (this.options === undefined || this.options.length < 1) {
            this.mutationObserverActive = true;
        }
        else {
            this.mutationObserverActive = false;
        }
    }
    debounceChanged() {
        this.balChange = debounceEvent(this.balChange, this.debounce);
    }
    async valueChanged(newValue, oldValue) {
        if (newValue !== oldValue) {
            this.onOptionChange();
        }
    }
    /**
     * LIFECYCLE
     * ------------------------------------------------------
     */
    connectedCallback() {
        this.debounceChanged();
        this.mutationObserverActive = this.options === undefined || this.options.length < 1;
    }
    componentDidLoad() {
        this.onOptionChange();
    }
    mutationListener() {
        this.onOptionChange();
    }
    breakpointListener(breakpoints) {
        this.isMobile = breakpoints.mobile;
    }
    swiperOnChange(index) {
        // this.value = index
        // this.balChange.emit(index)
    }
    /**
     * PUBLIC METHODS
     * ------------------------------------------------------
     */
    /**
     * Go to tab with the given value
     */
    async select(step) {
        this.value = step.value;
    }
    /**
     * Find the options properties by its value
     */
    async getOptionByValue(value) {
        const options = this.store;
        return options.find(option => option.value === value);
    }
    /**
     * PRIVATE METHODS
     * ------------------------------------------------------
     */
    get items() {
        return Array.from(this.el.querySelectorAll(`#${this.stepsId} > bal-step-item`));
    }
    isActive(step) {
        return step.value === this.value;
    }
    /**
     * RENDER
     * ------------------------------------------------------
     */
    render() {
        const block = BEM.block('steps');
        const bemStepsNav = block.element('nav');
        let hasPassed = true;
        let index = -1;
        const steps = this.store
            .map(step => (Object.assign(Object.assign({}, step), { active: step.value === this.value })))
            .map(step => {
            if (step.active) {
                hasPassed = false;
            }
            if (!step.invisible) {
                index = index + 1;
            }
            return Object.assign(Object.assign({}, step), { passed: hasPassed, index });
        });
        return (h(Host, { class: Object.assign({}, block.class()), "data-value": this.store
                .filter(t => this.isActive(t))
                .map(t => t.value)
                .join(','), "data-label": this.store
                .filter(t => this.isActive(t))
                .map(t => t.label)
                .join(',') }, h("nav", { class: Object.assign({}, bemStepsNav.class()), role: "tablist", "aria-live": "polite" }, steps
            .filter(step => !step.invisible)
            .map(step => (h(StepButton, { item: step, color: this.color, isMobile: this.isMobile, clickable: this.clickable && !step.disabled, onSelectTab: this.onSelectTab })))), h("div", { id: this.stepsId, class: Object.assign({}, block.element('steps__content').class()) }, h("slot", null))));
    }
    static get is() { return "bal-steps"; }
    static get originalStyleUrls() {
        return {
            "$": ["bal-steps.sass"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["bal-steps.css"]
        };
    }
    static get properties() {
        return {
            "options": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "BalStepOption[]",
                    "resolved": "BalStepOption[]",
                    "references": {
                        "BalStepOption": {
                            "location": "import",
                            "path": "./bal-step.type",
                            "id": "src/components/bal-steps/bal-step.type.ts::BalStepOption"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Steps can be passed as a property or through HTML markup."
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "clickable": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If `true` the tabs or steps can be clicked."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "clickable",
                "defaultValue": "true"
            },
            "color": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "BalProps.BalStepsColor",
                    "resolved": "\"green\" | \"light-blue\" | \"primary\" | \"purple\" | \"red\" | \"yellow\"",
                    "references": {
                        "BalProps": {
                            "location": "global",
                            "id": "global::BalProps"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Defines the color of the steps so it can be placed on colored backgrounds"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "color",
                "defaultValue": "'primary'"
            },
            "debounce": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Set the amount of time, in milliseconds, to wait to trigger the `balChange` event after each keystroke. This also impacts form bindings such as `ngModel` or `v-model`."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "debounce",
                "defaultValue": "0"
            },
            "value": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Value of the current active step"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "value",
                "defaultValue": "undefined"
            }
        };
    }
    static get states() {
        return {
            "store": {},
            "isMobile": {}
        };
    }
    static get events() {
        return [{
                "method": "balChange",
                "name": "balChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the changes has finished."
                },
                "complexType": {
                    "original": "BalEvents.BalTabsChangeDetail",
                    "resolved": "string",
                    "references": {
                        "BalEvents": {
                            "location": "global",
                            "id": "global::BalEvents"
                        }
                    }
                }
            }];
    }
    static get methods() {
        return {
            "select": {
                "complexType": {
                    "signature": "(step: BalStepOption) => Promise<void>",
                    "parameters": [{
                            "name": "step",
                            "type": "BalStepOption",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "BalStepOption": {
                            "location": "import",
                            "path": "./bal-step.type",
                            "id": "src/components/bal-steps/bal-step.type.ts::BalStepOption"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Go to tab with the given value",
                    "tags": []
                }
            },
            "getOptionByValue": {
                "complexType": {
                    "signature": "(value: string) => Promise<BalStepOption>",
                    "parameters": [{
                            "name": "value",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "BalStepOption": {
                            "location": "import",
                            "path": "./bal-step.type",
                            "id": "src/components/bal-steps/bal-step.type.ts::BalStepOption"
                        }
                    },
                    "return": "Promise<BalStepOption>"
                },
                "docs": {
                    "text": "Find the options properties by its value",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "options",
                "methodName": "optionChanged"
            }, {
                "propName": "debounce",
                "methodName": "debounceChanged"
            }, {
                "propName": "value",
                "methodName": "valueChanged"
            }];
    }
}
__decorate([
    Logger('bal-steps'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Function]),
    __metadata("design:returntype", void 0)
], Steps.prototype, "createLogger", null);
__decorate([
    ListenToMutation({ tags: ['bal-steps', 'bal-step-item'] }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], Steps.prototype, "mutationListener", null);
__decorate([
    ListenToBreakpoints(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], Steps.prototype, "breakpointListener", null);
let StepsIds = 0;
