/// <reference path="./definition.d.ts" />

import * as React from 'react';
import classNames from 'classnames';

const element = {};
const prefix = 'tsp-component-Accordion';
class Accordion extends React.Component<TspComponentAccordionProps, TspComponentAccordionState> {
  constructor(props: TspComponentAccordionProps, state: TspComponentAccordionState) {
    super(props, state);
  }

  public elem: HTMLElement;
  public height: number;
  public state: TspComponentAccordionState = {
    open: this.props.defaultOpen
  };

  public componentDidMount(): void {
    this.elem = this.refs.elem as HTMLElement;
    element[this.props.id] = this.elem;
    if (this.props.defaultOpen) {
      this.elem.dataset.height = this.elem.clientHeight.toString();
      this.elem.style.height = this.elem.dataset.height + 'px';
    } else {
      this.elem.dataset.height = '0';
      this.elem.style.height = '0px';
    }
  }

  public componentDidUpdate(nextProps: TspComponentAccordionProps): void {
    if (this.props.updateId !== nextProps.updateId) {
      this.elem.style.height = 'auto';
      this.elem.dataset.height = this.elem.clientHeight.toString();
      this.elem.style.height = this.elem.dataset.height + 'px';
    }
  }

  public render(): JSX.Element {
    return (
      <div
        id={this.props.id}
        ref="elem"
        className={classNames({
          [prefix]: true,
          [`${prefix}-hidden`]: !this.state.open,
          [this.props.className]: this.props.className
        })}
      >
        {this.props.children}
      </div>
    );
  }
}

function accordionOpen(id: string): void {
  const elem = element[id];
  elem.classList.add(`${prefix}-animation`);
  elem.classList.remove(`${prefix}-hidden`);
  setTimeout(() => {
    elem.classList.remove(`${prefix}-animation`);
    elem.dataset.hidden = 'false';
  }, 300);
}

function accordionClose(id: string): void {
  const elem = element[id];
  elem.classList.add(`${prefix}-animation`);
  elem.classList.add(`${prefix}-hidden`);
  setTimeout(() => {
    elem.classList.remove(`${prefix}-animation`);
    elem.dataset.hidden = 'true';
  }, 300);
}

export { Accordion, accordionOpen, accordionClose };