/**
 * closable.js
 * Script closes element incl animation
 */

import ElementHelpers from '../helpers/element-helpers';

/**
 * Declare constants
 */
const attributeBase = 'data-rs-closable';

export class Closable {
  constructor(element) {
    this.element = element;
    this.elements = ElementHelpers.getElementsByAttribute(
      this.element.getAttribute(attributeBase)
    );
    this.addEventHandlers();
  }

  /**
   * Declare classes
   */
  get classes() {
    return {
      closableClosed: 'closable--closed'
    };
  }

  /**
   * Add event handlers
   */
  addEventHandlers() {
    this.element.addEventListener('click', (clickEvent) => {
      clickEvent.preventDefault();
      if (this.elements.length > 0) {
        this.elements.forEach((element) => {
          if (
            element.scrollHeight > 0 &&
            !element.classList.contains(this.classes.closableClosed)
          ) {
            element.style.maxHeight = `${element.scrollHeight}px`;
          }
          element.classList.add(this.classes.closableClosed);
          element.style.maxHeight = '0px';
          setTimeout(() => {
            element.remove();
          }, 700);
        });
      }
    });
    // set max height on window load, to prevent max height is too low caused by slow loading elements
    window.addEventListener('load', () => {
      this.setMaxHeightElements();
    });
    // on window resize, set max height elements
    window.addEventListener('resize', () => {
      this.setMaxHeightElements();
    });
  }

  /**
   * Set max height elements
   */
  setMaxHeightElements() {
    if (this.elements.length > 0) {
      this.elements.forEach((element) => {
        if (
          element.scrollHeight > 0 &&
          !element.classList.contains(this.classes.closableClosed)
        ) {
          element.style.maxHeight = 'none';
          element.style.maxHeight = `${element.scrollHeight}px`;
        }
      });
    }
  }

  /**
   * Get selector
   */
  static getSelector() {
    return '[' + attributeBase + ']';
  }
}
