import { Integration } from './integration.class';

/**
 * Integration that removes the given element from DOM if both, a start and an
 * end date have been selected.
 */
export class RemoveElementIfDateSelected extends Integration {

    /**
     * @param {HTMLElement} node
     * @returns {boolean}
     */
    static test(node) {
        return node.hasAttribute('data-toubiz-date-picker-integration.remove-element-if-date-selected');
    }

    initialize() {
        const selector = this.node.getAttribute('data-toubiz-date-picker-integration.remove-element-if-date-selected');
        const element = document.querySelector(selector);
        const nextSibling = element.nextSibling;

        this.node.addEventListener('toubiz-date-picker.change', event => {
            const remove = !!(event.detail.range.start && event.detail.range.end);

            if (remove && element.parentNode) {
                element.parentNode.removeChild(element);
            }

            if (!remove && nextSibling.parentNode) {
                nextSibling.parentElement.insertBefore(element, nextSibling);
            }
        });
    }

}
