import { fireEvent } from '@nimius/event-utility';

export default class ToubizExpandableText {

    // TODO Make toubiz-expandable-text independent (currently depending on target-enhance)

    /**
     * @private
     * @type {HTMLElement}
     */
    node;

    /**
     * @private
     * @type {string}
     */
    labelOpen;

    /**
     * @private
     * @type {string}
     */
    labelClose;

    /**
     * @private
     * @type {HTMLElement}
     */
    labelNode;

    constructor(node) {
        /** @private {HTMLElement} */
        this.node = node;

        /** @private {string} */
        this.labelOpen = node.getAttribute('data-toubiz-expandable-text-label-open');

        /** @private {string} */
        this.labelClose = node.getAttribute('data-toubiz-expandable-text-label-close');

        /** @private {HTMLElement} */
        this.labelNode = node.querySelector('[data-toubiz-expandable-text-label]');

        this.init();
    }

    init() {
        if (this.labelNode && this.labelOpen && this.labelClose) {
            this.onToggle();
            this.node.addEventListener('click', () => this.onToggle(), false);
            /*
            * Using note `href` attribute (if present) to refer to the matching expand container.
            * Should the container not exceed its maximum height no toggle is required,
            * hence the button will be hidden.
            * fireEvent is used to toggle once in order to avoid 'collapsed' markup look.
            * */
            if (this.node.hasAttribute('href')) {
                const href = this.node.getAttribute('href').substring(1);
                const expandContainer = document.getElementById(href);
                if (expandContainer.offsetHeight === expandContainer.scrollHeight) {
                    setTimeout(() => {
                        fireEvent(this.node, 'target-enhancement.open');
                        this.node.classList.add('hidden');
                    }, 0);
                }
            }
        }
    }

    onToggle() {
        /*
         * Use setTimeout setTimeout() to re-queue the new JavaScript at the end
         * of the execution queue. It gives the browser a chance to finish doing
         * some non-JavaScript things, like setting the data-attribute in this case.
         */
        setTimeout(() => {
            const currentState = this.node.getAttribute('aria-expanded');
            this.labelNode.innerHTML = currentState === 'true' ? this.labelClose : this.labelOpen;
        }, 0);
    }

}
