import { Subscription } from 'rxjs';

import { Component, ViewChild, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Store, select } from '@ngrx/store';

import { MatTabChangeEvent, MatTabGroup } from '@angular/material/tabs';
import { MatSidenav } from '@angular/material/sidenav';

import { LogService } from '@ucap/ng-logger';

import { AppSelector } from '@app/store/state';

const NAVS = ['group', 'chat', 'organization', 'message'];

@Component({
  selector: 'app-layouts-default',
  templateUrl: './default.layout.component.html',
  styleUrls: ['./default.layout.component.scss']
})
export class DefaultLayoutComponent implements OnInit, OnDestroy {
  @ViewChild('navTabGroup', { static: true })
  navTabGroup: MatTabGroup;

  @ViewChild('leftSidenav', { static: true })
  leftSidenav: MatSidenav;

  private windowSizeSubscription: Subscription;

  constructor(
    private router: Router,
    private store: Store<any>,
    private logService: LogService
  ) {}

  ngOnInit(): void {
    this.windowSizeSubscription = this.store
      .pipe(select(AppSelector.windowSize))
      .subscribe((size) => {
        if (size.width < 780) {
          if (this.leftSidenav.opened) {
            this.leftSidenav.close();
          }
        } else {
          if (!this.leftSidenav.opened) {
            this.leftSidenav.open();
          }
        }
      });

    this.setTabGroup(this.router.url);
  }

  ngOnDestroy(): void {
    if (!this.windowSizeSubscription) {
      this.windowSizeSubscription.unsubscribe();
    }
  }

  onSelectedTabChange(event: MatTabChangeEvent) {
    if (4 === event.index) {
      this.router.navigate(
        ['group', { outlets: { content: 'chat/index' } }],
        {}
      );
      return;
    }
    this.router.navigate([
      NAVS[event.index],
      { outlets: { content: 'index' } }
    ]);
  }

  onClickToggleLeftSidenav() {
    if (this.leftSidenav.opened) {
      this.leftSidenav.close();
    } else {
      this.leftSidenav.open();
    }
  }

  private setTabGroup(url: string) {
    this.navTabGroup.selectedIndex = NAVS.findIndex((v) =>
      url.startsWith(`/${v}`)
    );
  }
}
