import { Component } from '@angular/core';
import { NavigationStart, Router, RouterOutlet } from '@angular/router';
import { CoreModule } from '@core/core.module';
import { MyDirectiveModule } from '@core/directives/my-directive.module';
import { StyleClassModule } from 'primeng/styleclass';
import { Subscription, tap } from 'rxjs';
import { AuthService } from './core/services';

@Component({
  selector: 'app-root',
  imports: [CoreModule, RouterOutlet, MyDirectiveModule, StyleClassModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
})
export class AppComponent {
  title = 'Browser-Strutture-Musa';
  routerEvent$: Subscription;

  constructor(
    private authService: AuthService,
    private router: Router,
  ) {
    this.routerEvent$ = this.router.events
      .pipe(
        tap((e) => {
          if (e instanceof NavigationStart) {
            const url = e.url;
            if (
              !url.split('/')[1].startsWith('login') &&
              !url.split('/')[1].startsWith('public')
            ) {
              this.authService.populate()?.subscribe();
              this.routerEvent$.unsubscribe();
            }
          }
        }),
      )
      .subscribe();
  }
}
