import { Injectable } from '@angular/core';
import { environment } from "../../environments/environment";
import { HttpClient, HttpEvent } from "@angular/common/http";
import { Observable } from "rxjs";
import { Professor } from "../model/Professor"; // Ensure this model is correctly defined
import { CustomHttpResponse } from "../dto/custom-http-response";
import { map } from "rxjs/operators";

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

  private host: string = environment.apiUrl;
  private storage = localStorage;

  private selectedProfessor: Professor;

  constructor(private httpClient: HttpClient) {
  }

  public getAllProfessors(): Observable<ProfessorPage> {
    return this.httpClient
      .get<ProfessorPage>(`${this.host}/professor?size=2147483647`);
  }

  public addProfessor(formData: FormData): Observable<Professor> {
    return this.httpClient
      .post<Professor>(`${this.host}/professor/add`, formData);
  }

  public updateProfessor(professorId: string, formData: FormData): Observable<Professor> {
    return this.httpClient
      .put<Professor>(`${this.host}/professor/${professorId}`, formData);
  }

  public deleteProfessor(professorId: string): Observable<CustomHttpResponse> {
    return this.httpClient
      .delete<CustomHttpResponse>(`${this.host}/professor/${professorId}`);
  }

  public updateProfileImage(professorId: string, formData: FormData): Observable<HttpEvent<Professor>> {
    return this.httpClient
      .put<Professor>(`${this.host}/user/${professorId}/profile-image`, formData,
        {
          reportProgress: true,
          observe: 'events'
        });
  }

  public addProfessorsToLocalStorage(professors: Professor[]) {
    this.storage.setItem('professors', JSON.stringify(professors));
  }

  public getProfessorsFromLocalStorage(): Professor[] {
    let professors = this.storage.getItem('professors');
    if (professors) {
      return JSON.parse(professors);
    }
    return [];
  }

  public createProfessorFormData(professor: Professor, profileImage: File | null): FormData {
    const formData = new FormData();

    formData.append('firstName', professor.firstName);
    formData.append('lastName', professor.lastName);
    formData.append('email', professor.email);
    formData.append('department', professor.department);
    formData.append('position', professor.position);
    formData.append('officeLocation', professor.officeLocation);
    formData.append('status', professor.status);
    // formData.append('joinDate', professor.joinDate.toString()); // Convert LocalDateTime to string
    if (profileImage)
      formData.append('profileImage', profileImage);

    return formData;
  }

  public setSelectedProfessor(professor: Professor): void {
    this.selectedProfessor = professor;
  }

  public getSelectedProfessor(): Professor {
    return this.selectedProfessor;
  }

  public findProfessorById(id: string): Professor | Observable<Professor> {
    let cachedProfessors = this.getProfessorsFromLocalStorage();
    const foundProfessor = cachedProfessors.find((p) => p.professorId === id);

    if (foundProfessor) return foundProfessor;

    return this.getAllProfessors()
      .pipe(
        map((page: ProfessorPage) => page.content),
        map(professors => professors.find(p => p.professorId === id)!)
      );
  }
}

export interface ProfessorPage {
  content: Professor[];
  last: boolean;
  first: boolean;
  totalElements: number;
  size: number;
  numberOfElements: number;
  number: number;
  empty: boolean;
}
