import { Component } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';
import { NgCortexService } from '@ng-cortex/core';

@Component({
  selector: 'nc-side',
  templateUrl: './nc-side.component.html',
  styleUrls: ['./nc-side.component.scss'],
  animations: [
    trigger('menuUnfolded', [
      state('true', style({ height: '*' })),
      state('false', style({ height: '0px' })),
      transition('false <=> true', animate(200))
    ])
  ]
})
export class NcSideComponent {

  _autoCollapsed = false;

  private _collapseMenuTransition: () => void = null;

  constructor(
    public ncSrv: NgCortexService
  ) { }

  _expandMenu(event: MouseEvent) {
    if (this._autoCollapsed && !this._collapseMenuTransition) {
      const element = (event.target as HTMLElement).parentElement;
      this._collapseMenuTransition = () => element.classList.add(`_nc-side-menu-expand-done`);
      element.addEventListener(`transitionend`, this._collapseMenuTransition);
      element.classList.add(`_nc-side-menu-expand-start`);
    }
  }

  _collapseMenu(event: MouseEvent) {
    if (this._collapseMenuTransition) {
      const element = (event.target as HTMLElement).firstElementChild;
      element.removeEventListener(`transitionend`, this._collapseMenuTransition);
      element.classList.remove(`_nc-side-menu-expand-start`);
      element.classList.remove(`_nc-side-menu-expand-done`);
      this._collapseMenuTransition = null;
    }
  }

  _toggleAutoCollapsed(event: MouseEvent) {
    this._autoCollapsed = !this._autoCollapsed;
    if (this._collapseMenuTransition) {
      let element = event.target as HTMLElement;
      while (!element.classList.contains(`_nc-side-menu-wrap`)) {
        element = element.parentElement;
      }
      element.removeEventListener(`transitionend`, this._collapseMenuTransition);
      element.classList.remove(`_nc-side-menu-expand-start`);
      element.classList.remove(`_nc-side-menu-expand-done`);
      this._collapseMenuTransition = null;
    }
  }

}
