import { Component, ViewChild,
  ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core'
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'
import { Router, NavigationEnd } from '@angular/router';
import { MatSidenav } from '@angular/material/sidenav'
import { Observable } from 'rxjs'
import { map, shareReplay, withLatestFrom, filter } from 'rxjs/operators'

import { DataService } from '../data.service'
import { ConfigService } from '../config.service'

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.scss'],
})
export class NavComponent {
  @ViewChild('drawer') drawer: MatSidenav;
  isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset)
    .pipe(
      map(result => result.matches),
      shareReplay()
    )

  constructor(
    private breakpointObserver: BreakpointObserver,
    public dataService: DataService,
    public router: Router,
    public configService: ConfigService,
  ) {
    router.events.pipe(
      withLatestFrom(this.isHandset$),
      filter(([a, b]) => b && a instanceof NavigationEnd)
    ).subscribe(_ => this.drawer.close())
  }
}
