import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, firstValueFrom } from 'rxjs';
import { Router } from '@angular/router';
import Swal from 'sweetalert2';
import { UrlService } from './url.service';

@Injectable({
  providedIn: 'root',
})
export class AuthenticationService {

  private loginUrl: string;
  private logoutUrl: string;
  private checkUrl: string;

  constructor(
    private router: Router,
    private http: HttpClient,
    urlService : UrlService)
    { 
      this.loginUrl = urlService.apiRoute.login;
      this.logoutUrl = urlService.apiRoute.logout;
      this.checkUrl = urlService.apiRoute.loginCheck;
    }

  async isAuthenticated(): Promise<boolean> {
    try {
      const response = await firstValueFrom(this.http.get<boolean>(this.checkUrl, { withCredentials: true }));
      _isLogedIn = response;
      return response;
    } catch (error) {
      this.showErrorAlert();
      return false;
    }
  }

  login(username: string, password: string): Observable<any> {
    return new Observable(observer => {
      const userData = { username, password };

      this.http.post<any>(this.loginUrl, userData, { withCredentials: true })
        .subscribe({
          next: (response) => {
            _isLogedIn = true;
            observer.next(response);
          },
          error: (error) => {
            this.showErrorAlert()
            observer.error(error);
          },
          complete: () => {
            observer.complete();
          }
        });
    });
  }

  logout(): Observable<any> {
    return new Observable(observer => {
      this.http.post<any>(this.logoutUrl, {}, { withCredentials: true })
        .subscribe({
          next: (response) => {
            this.router.navigate(['/']);
            _isLogedIn = false;
            observer.next(response)
          },
          error: (error) => observer.error(error),
          complete: () => observer.complete()
        });
    });
  }

  showErrorAlert() {
    Swal.fire({
      icon: "error",
      title: "Oops...",
      text: "Der Server antwortet nicht.",
    });
  }
}

let _isLogedIn: boolean = false;
export const IsLogedIn = () => _isLogedIn