/**
 * collapsible.js
 * Script to expand and collapse elements
 */

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

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

export class Collapsible {
  constructor(element) {
    this.element = element;
    this.content = this.element.parentElement.querySelector(
      `[${this.attributes.content}]`
    );
    this.triggerElement = this.element;
    this.initialExpanded =
      this.content.getAttribute(this.attributes.content) ===
      this.states.expanded;

    this.addEventHandlers();
    if (this.initialExpanded) {
      this.handleExpandedElement();
    }
  }

  /**
   * Declare attribute constants
   */
  get attributes() {
    return {
      content: `${attributeBase}-content`,
      button: `${attributeBase}-button`,
      expanded: `${attributeBase}-expanded`,
      navigation: 'navigation',
      ariaExpanded: 'aria-expanded',
      ariaHidden: 'aria-hidden',
      filter: 'filter',
      closeOnOutsideClick: `${attributeBase}-close-on-outside-click`,
      closeOnScroll: `${attributeBase}-close-on-scroll`
    };
  }

  /**
   * Declare classes
   */
  get classes() {
    return {
      collapsibleTriggerExpanded: 'collapsible__trigger--expanded'
    };
  }

  /**
   * Declare state constants
   */
  get states() {
    return {
      expanded: 'expanded'
    };
  }

  /**
   * Add event handlers
   */
  addEventHandlers() {
    const initialHeight = this.content.offsetHeight;

    if (
      this.element.getAttribute(attributeBase) === this.attributes.navigation
    ) {
      this.triggerElement = this.element.querySelector(
        `[${this.attributes.button}]`
      );
    }

    if (this.triggerElement != null) {
      this.triggerElement.addEventListener('click', (clickEvent) => {
        clickEvent.preventDefault();
        this.toggle(initialHeight);
      });
    }
    if (this.initialExpanded) {
      window.addEventListener('load', () => {
        this.handleExpandedElement();
      });
    }

    this.isOverflown(this.content, this.element);

    // on orientation change, recalculate content height
    window.addEventListener('orientationchange', () => {
      this.recalculateContentHeight();
      this.isOverflown(this.content, this.element);
    });

    window.addEventListener('resize', () => {
      this.recalculateContentHeight();
      this.isOverflown(this.content, this.element);
    });

    window.addEventListener('scroll', () => {
      this.simulateClickOnScroll();
    });
  }

  /*
   * function to get all the elements that needs to be closed on scroll and are currently expanded
   */
  isExpanedElementToClose() {
    const elementsToClose = ElementHelpers.getElementsByAttribute(
      this.attributes.closeOnScroll
    );

    if (!elementsToClose) {
      return;
    }

    let elArr = [];

    elementsToClose.forEach((element) => {
      if (
        element.classList.contains(this.classes.collapsibleTriggerExpanded) &&
        element.hasAttribute(this.attributes.closeOnScroll)
      ) {
        elArr.push(element);
      }
    });

    return elArr;
  }

  /*
   * if the element is expanded and needs to be closed on scroll, simulate a click
   */
  simulateClickOnScroll() {
    const elements = this.isExpanedElementToClose();

    const windowScrollPos = window.scrollY;

    elements.forEach((element) => {
      const elementPos = element.parentElement.offsetTop;

      if (windowScrollPos > elementPos) {
        console.log('simulate click');
        element.click();
      }
    });
  }

  toggle(initialHeight) {
    if (this.isTriggerExpanded) {
      this.collapseTrigger();
      this.collapseContent(initialHeight);
    } else {
      const contentHeight = this.content.scrollHeight;
      this.expandTrigger();
      this.expandContent(contentHeight);
    }
  }

  handleExpandedElement() {
    if (ElementHelpers.isDesktop()) {
      const contentHeight = this.content.scrollHeight;
      if (this.content.style.maxHeight !== `${contentHeight}px`) {
        this.expandContent(contentHeight);
        this.expandTrigger();
      }
      if (this.initialExpanded === false) {
        this.content.setAttribute(
          this.attributes.content,
          this.attributes.filter
        );
        this.element.setAttribute(
          this.attributes.expanded,
          this.states.expanded
        );
      }
    } else {
      // do not collapse on mobile devices if in filter
      this.collapseTrigger();
      this.collapseContent();
    }
  }

  get isTriggerExpanded() {
    return this.element.classList.contains(
      this.classes.collapsibleTriggerExpanded
    );
  }

  collapseTrigger() {
    this.element.classList.remove(this.classes.collapsibleTriggerExpanded);
    this.element.setAttribute(this.attributes.ariaExpanded, 'false');
    this.element.removeAttribute(this.attributes.expanded);
  }

  collapseContent(initialHeight) {
    this.content.style.maxHeight = initialHeight + 'px';
    this.content.setAttribute(this.attributes.content, '');
    this.content.setAttribute(this.attributes.ariaHidden, 'true');
  }

  /**
   * Handles element on expand - add class and set aria expanded attribute
   */
  expandTrigger() {
    this.element.classList.add(this.classes.collapsibleTriggerExpanded);
    this.element.setAttribute(this.attributes.ariaExpanded, 'true');
  }

  /**
   * Handles content on expand - set maxheight, expanded state en aria hidden attribute
   *
   * @param {number} contentHeight - height of content element
   */
  expandContent(contentHeight) {
    this.content.style.maxHeight = `${contentHeight + 30}px`; // add 30px to fit on IOS mobile (gives back different scrollHeight)
    this.content.setAttribute(this.attributes.content, this.states.expanded);
    this.content.setAttribute(this.attributes.ariaHidden, 'false');
  }

  /**
   * Recalculate content height and set max height
   */
  recalculateContentHeight() {
    this.content = this.element.parentElement.querySelector(
      `[${this.attributes.content}]`
    );
    this.contentHeight = this.content.scrollHeight;

    // set maxheight on expanded content
    if (
      this.content.getAttribute(this.attributes.content) ===
      this.states.expanded
    ) {
      this.content.style.maxHeight = `${this.contentHeight}px`;
    }
  }

  /**
   * check if the content is not overflown
   */
  isOverflown(content, trigger) {
    if (trigger.getAttribute(attributeBase) === 'hide-trigger') {
      const isOverflown =
        content.scrollHeight > content.clientHeight ||
        content.scrollWidth > content.clientWidth;

      if (!isOverflown) {
        trigger.classList.add('display-none');
      }

      if (isOverflown) {
        trigger.classList.remove('display-none');
      }
    }
  }

  /**
   * Get selector
   */
  static getSelector() {
    return `[${attributeBase}]`;
  }
}
