import ScreenSizeDetection from '../ScreenSizeDetection';
import { ToolbarService } from './toolbar.service';
import { Utils } from '../Utils';

export class ToolbarController {

  private listItems: NodeListOf<Element>;
  private mainElement: Element;
  private backdropClass: string = 'sidenav-active';
  private eventName: string;

  public toolbarService: any;

  constructor(
    private $element
  ) {
    this.toolbarService = ToolbarService;
    this.listItems = this.$element[0].querySelectorAll('ul li');
    this.mainElement = document.getElementById('maincontent');
    this.eventName = (Utils.isTouchDevice()) ? 'touchstart' : 'click';
    this.subscribeScreensize();
  }

  private subscribeScreensize() {
    ScreenSizeDetection.get().subscribe(screensize => {
      if (screensize === 'xs' || screensize === 'sm') {
        this.start();
      } else {
        this.destroy();
      }
    });
  }

  private start() {
    for (let index = 0; index < this.listItems.length; index++) {
      let element = this.listItems[index];
      element.addEventListener(this.eventName, this.toggleMenu);
    }
  }

  private destroy() {
    for (let index = 0; index < this.listItems.length; index++) {
      let element = this.listItems[index];
      element.removeEventListener(this.eventName, this.toggleMenu);
    }
  }

  private toggleMenu(e) {
    e.stopPropagation();
    e.currentTarget.classList.toggle('active');
    this.mainElement.classList.toggle(this.backdropClass);
  }

  public toggleSidenav() {
    this.toolbarService.sidenavActive = !this.toolbarService.sidenavActive;
    Utils.toggleNoScrollBodyState();
  }
}
