import * as Messages from "/services/messages/messages.js";

let candidateModel;

export function getCandidateModel() {
  if (candidateModel == null) {
    candidateModel = new CandidateModel();
  }
  return candidateModel;
}

class CandidateModel {
  constructor() {}

  async getCandidate(id) {
    if (this.candidates == null) await this.refreshCandidates();
    let candidateToGet;
    this.candidates.forEach((candidate) => {
      if (candidate.ID == id) candidateToGet = candidate;
    });
    return candidateToGet;
  }

  async getCandidates() {
    if (this.candidates == null) {
      try {
        const response = await fetch("/api/Candidate/", {
          method: "GET",
          headers: new Headers({
            "XSRF-Token": this.current_user.xsrftoken,
          }),
        });
        if (response.status !== 200) {
          throw new Error(
            `Candidates could not be fetched (status ${response.status})`
          );
        }
        this.candidates = await response.json();
      } catch (e) {
        Messages.Show("is-warning", e.message);
        console.error(e);
      }
    }
    return this.candidates;
  }

  async saveCandidate(
    method,
    ID,
    CandidateListID,
    FullName,
    Rank,
    CommunityCounseller,
    Birthdate,
    PotentialIncompatibility,
    Refused,
    Removed
  ) {
    try {
      const response = await fetch("/api/Candidate/" + ID, {
        method: method,
        headers: new Headers({
          "XSRF-Token": this.current_user.xsrftoken,
        }),
        body: JSON.stringify({
          ID: ID,
          CandidateListID: CandidateListID,
          FullName: FullName,
          Rank: Rank,
          CommunityCounseller: CommunityCounseller,
          Birthdate: Birthdate,
          PotentialIncompatibility: PotentialIncompatibility,
          Refused: Refused,
          Removed: Removed,
        }),
      });
      if (response.status !== 200) {
        throw new Error(
          `Candidate could not be updated or created (status ${response.status})`
        );
      }
      this.refreshCandidates();
      return await response.json();
    } catch (e) {
      Messages.Show("is-warning", e.message);
      console.error(e);
      return;
    }
  }

  async deleteCandidate(ID) {
    try {
      const response = await fetch("/api/Candidate/" + ID, {
        method: "delete",
        headers: new Headers({
          "XSRF-Token": this.current_user.xsrftoken,
        }),
      });
      if (response.status !== 200) {
        throw new Error(
          `Candidate could not be deleted (status ${response.status})`
        );
      }
    } catch (e) {
      Messages.Show("is-warning", e.message);
      console.error(e);
    }
    await this.refreshCandidates();
  }

  async refreshCandidates() {
    this.candidates = null;
    await this.getCandidates();
  }
}