import { Injectable, Inject, Output, signal, computed, Signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { BehaviorSubject, Observable } from 'rxjs';
import { ConfigureUrl, User } from '../models';
import { Utils, AppSettingService, LookupService } from '../shares';


@Injectable({ providedIn: 'root' })
export class AuthenticationService {
  //private authChange = new BehaviorSubject<User>(new User());
 // public currentUser: Observable<User>;
 public authChange = signal(new User());
 
  private _isHome = false;
  private _isReport = false;
  private _selectDate: Date | null = null;
  baseUrl = ''; // this.appSettingService.appSetting.baseUrl + "/"+ ConfigureUrl.loginApiUrl;
  constructor(private http: HttpClient,
    private appSetting: AppSettingService,
    private lookupService: LookupService,

  ) {
    // this default when load look for previous login information
    // if no need then comment out downthere
   // this.currentUser = this.authChange.asObservable();
    const fname = this.getCurrentUser();
    if (fname) {

      this.authChange.set(fname);
    }

  }


  /* select date */
  public get SelectDate(): Date | null {
    return this._selectDate;
  }
  public set SelectDate(value: Date | null) {
    this._selectDate = value;
  }

  public get isHome(): boolean {
    return this._isHome;
  }
  public set isHome(value: boolean) {
    if (value) {
      this._isReport = false;
    }
    this._isHome = value;
  }

  public get isReport(): boolean {
    return this._isReport;
  }
  public set isReport(value: boolean) {
    if (value) {
      this._isHome = false;
    }
    this._isReport = value;
  }

  login(username: string, password: string): Observable<any> {
    this.lookupService.setAllNull();

    const url = this.appSetting.appSetting.baseUrl + "/" + ConfigureUrl.loginApiUrl;
    const epass = btoa(password);
    return this.http.post<any>(url, { username, password: epass })
      .pipe(map(resultModel => {
        // login successful if there's a jwt token in the response
        if (resultModel.statusCode == 1) {
          const user = resultModel.data;
         
          Utils.setLocalStore(user);
          // const fName = user.firstName + " " + user.lastName;
          this.authChange.set(user);
          console.log("login from API result ", this.authChange());

        }
        return resultModel;
      }));
  }

  getCurrentUser(): User {
    let userObj: User;
    userObj = new User();
    let user = sessionStorage.getItem('currentUser');
    if (user) {
      userObj = JSON.parse(user);
      //fname = userObj.firstName + " " + userObj.lastName;
      // logged in so return true      
    }
    return userObj;
  }

  isAuth(): boolean {
    let val: boolean;
    val = false;
    if (sessionStorage.getItem('currentUser')) {
      // logged in so return true
      val = true;
    }
    return val;
  }
  logout(): void {
    this.lookupService.setAllNull();

    const url = this.appSetting.appSetting.baseUrl + "/" + ConfigureUrl.logoutUrl;
    this.http.post<any>(url, {}).subscribe({
      next: x => {
        // console.log("logout return", x);
        sessionStorage.removeItem('currentUser');
        const user = new User();
        this.authChange.set(user);
      },
      error: e => {
        sessionStorage.removeItem('currentUser');
        this.authChange.set(new User());
      }
    });

  }
}
