import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, NavigationStart, Router, RouterOutlet } from '@angular/router';
import { ConfigurationService } from './website/shared/services/configuration.service';
import { BehaviorSubject, filter, Subscription } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';
// import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent implements OnInit {
  title = 'Credit';
  static text: string;
  // private subscription!: Subscription;
  // private credentialSubject = new BehaviorSubject<any>(null);
  // private isConfigurationFetched = new BehaviorSubject<boolean>(false);

  constructor(
    private configurationService: ConfigurationService,
    private router: Router,
    private actRoute: ActivatedRoute,
    // private translate: TranslateService,

  ) { }
  async ngOnInit() {
    let language = localStorage.getItem('selectedLanguage');
    if (!language) {
      localStorage.setItem("selectedLanguage", "en")
    }
    // this.actRoute.url.subscribe(urlSegments => {
    //   console.log('Current route segments:', urlSegments.map(segment => segment.path).join('/'));
    // });
    // this.translate.use(language);
    // this.subscription = this.router.events.pipe(
    //   filter(event => event instanceof NavigationEnd)
    // ).subscribe(() => {
    //   this.getConfiguration();
    //   this.handleNavigation();
    // });
    await this.getConfiguration();
  }

  // ngOnDestroy() {
  //   if (this.subscription) {
  //     this.subscription.unsubscribe();
  //   }
  // }

  public async getConfiguration() {
    try {
      const res = await this.configurationService.getConfiguration();
      if (res && res.status == 200) {
        if (res.recordList[0].isTakeHostDetail) {
          this.router.navigate(['configuration']);
        } else {
          await this.navigateToRouteBasedOnConfiguration();
        }
      } else {
        this.router.navigate(['configuration']);
      }
    } catch (error) {
      this.router.navigate(['configuration']);
      console.log(error);
    }
  }

  private navigateToRouteBasedOnConfiguration() {
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe((event: NavigationEnd) => {
      const currentRoute = this.router.url;
      const searchString = 'admin';
      if (currentRoute.includes(searchString)) {
        const credential = JSON.parse(sessionStorage.getItem("Credential") ?? 'null') as any;
        if (!credential || !credential.userId) {
          this.router.navigate(['admin/login']);
        }
      } else {
        if (currentRoute == '/') {
          this.router.navigate(['/']);
        }

      }
    });
  }
}
