import { Component, ElementRef, ViewChild } from '@angular/core';
import { Router, RouterModule, RouterOutlet, ActivatedRoute } from '@angular/router';
import { Authentication } from './services/Authentication';
import { CommonModule, Location } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { isDevMode } from '@angular/core';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet, CommonModule, RouterModule],
  templateUrl: './app.html',
  styleUrl: './app.css'
})
export class App {

  @ViewChild('companiesLink') companiesLink!: ElementRef<HTMLAnchorElement>;
  @ViewChild('jobsLink') jobLink!: ElementRef<HTMLAnchorElement>;
  @ViewChild('resumesLink') resumeLink!: ElementRef<HTMLAnchorElement>;

  devMode: boolean = false;

  constructor( private http: HttpClient, public auth: Authentication, private router: Router, private route: ActivatedRoute, private location: Location){
    
    this.devMode = isDevMode();
    
    this.route.queryParams.subscribe(params => {
      
      const loginToken = params['LoginToken'];
      console.log("LoginToken : " + loginToken);

      if (loginToken){
        this.http.post( "api/account/loginticket", JSON.stringify(loginToken), { headers: {'Content-Type': 'application/json'} } ).subscribe({
          next: data => {
            auth.getLoginState();
            const pathWithoutQuery = this.location.path().split('?')[0];
            this.location.replaceState(pathWithoutQuery);
          },
          error: err => {
            auth.getLoginState();
            const pathWithoutQuery = this.location.path().split('?')[0];
            this.location.replaceState(pathWithoutQuery);
          }
        })
      }else{
        auth.getLoginState();
      }

    });
  }

  ngAfterViewInit(){
    let ViewLinks = [ this.companiesLink, this.resumeLink, this.jobLink ];
    ViewLinks.forEach(link => {
      if (new URL(link.nativeElement.href).pathname === new URL(window.location.href).pathname){
        link.nativeElement.classList.add("active");
      }
    });
  }

}
