import { NavigationBreadcrumbsItem } from '@af/digi-ng/_navigation/navigation-breadcrumbs';
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { UnsubscribeDirective } from '@msfa-directives/unsubscribe.directive';
import { Employee } from '@msfa-models/employee.model';
import { Organization } from '@msfa-models/organization.model';
import { Role } from '@msfa-models/role.model';
import { AuthenticationService } from '@msfa-services/api/authentication.service';
import { UserService } from '@msfa-services/user.service';
import { mapPathsToBreadcrumbs } from '@msfa-utils/map-paths-to-breadcrumbs.util';
import { BehaviorSubject, Observable } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';

@Component({
  selector: 'msfa-layout',
  templateUrl: './layout.component.html',
  styleUrls: ['./layout.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LayoutComponent extends UnsubscribeDirective {
  @Input() showBreadCrumbs = true;
  selectedOrganization$: Observable<Organization> = this.userService.selectedOrganization$;
  user$: Observable<Employee> = this.userService.user$.pipe(filter(user => !!user));
  roles$: Observable<Role[]> = this.userService.userRoles$.pipe(filter(roles => !!roles));
  isLoggedIn$: Observable<boolean> = this.authenticationService.isLoggedIn$;
  userLoading$: Observable<boolean> = this.isLoggedIn$.pipe(
    filter(isLoggedIn => !!isLoggedIn),
    switchMap(() => this.userService.userLoading$)
  );
  private readonly _startBreadcrumb: NavigationBreadcrumbsItem = {
    text: 'Start',
    routerLink: '/',
  };
  private _breadcrumbsItems$ = new BehaviorSubject<NavigationBreadcrumbsItem[]>([this._startBreadcrumb]);

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private authenticationService: AuthenticationService,
    private userService: UserService
  ) {
    super();
    super.unsubscribeOnDestroy(
      this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe(() => {
        const urlTree = this.router.parseUrl(this.router.url);

        if (urlTree.queryParams.code) {
          void this.router.navigate([], {
            relativeTo: this.activatedRoute,
            queryParams: { code: null },
            queryParamsHandling: 'merge',
            replaceUrl: true,
          });
        }

        urlTree.queryParams = {};

        const paths = urlTree
          .toString()
          .split('/')
          .filter(path => !!path);
        this._breadcrumbsItems$.next(mapPathsToBreadcrumbs(paths, this._startBreadcrumb));
      })
    );
  }

  get breadcrumbsItems(): NavigationBreadcrumbsItem[] {
    return this._breadcrumbsItems$.getValue();
  }
}
