import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { AsyncPipe } from '@angular/common';
import { Component } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatToolbarModule } from '@angular/material/toolbar';
import {
  ActivatedRoute,
  NavigationEnd,
  Router,
  RouterLink,
  RouterLinkActive,
  RouterOutlet,
} from '@angular/router';
import { Observable, filter, map, shareReplay } from 'rxjs';
import { AvatarComponent } from '../avatar/avatar.component';
import { RoleDirective } from '../ms-authentication/role.directive';

@Component({
    selector: 'app-app-shell',
    imports: [
        MatButtonModule,
        MatIconModule,
        MatToolbarModule,
        MatSidenavModule,
        MatListModule,
        AvatarComponent,
        RouterOutlet,
        RouterLink,
        RouterLinkActive,
        AsyncPipe,
        RoleDirective,
    ],
    templateUrl: './app-shell.component.html',
    styleUrl: './app-shell.component.scss'
})
export class AppShellComponent {
  isHandset$: Observable<boolean>;

  title$: Observable<string>;

  constructor(
    private readonly breakpointObserver: BreakpointObserver,
    private readonly router: Router,
    private readonly activatedRoute: ActivatedRoute
  ) {
    this.isHandset$ = this.breakpointObserver.observe(Breakpoints.Handset).pipe(
      map((result) => result.matches),
      shareReplay()
    );
    
    this.title$ = this.router.events.pipe(
      filter((event) => event instanceof NavigationEnd),
      map(() => {
        let child = this.activatedRoute.firstChild;
        while (child) {
          if (child.snapshot.data?.['title']) {
            return child.snapshot.data['title'];
          } else if (child.firstChild) {
            child = child.firstChild;
          } else {
            return 'Avicenna Dashboard';
          }
        }
      })
    );
  }
}
