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

let areaModel;

export function getAreaModel() {
  if (areaModel == null) {
    areaModel = new AreaModel();
  }
  return areaModel;
}

class AreaModel {
  constructor() {}

  async getArea(id) {
    if (this.areas == null) await this.refreshAreas();
    let areaToGet;
    this.areas.forEach((area) => {
      if (area.ID == id) areaToGet = area;
    });
    return areaToGet;
  }

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

  async saveArea(method, ID, ElectionID, Name, SeatNumber) {
    try {
      const response = await fetch(
        "/api/Area/" + ID,
        {
          method: method,
          headers: new Headers({
            "XSRF-Token": this.current_user.xsrftoken,
          }),
          body: JSON.stringify({
            ID: ID,
            ElectionID: ElectionID,
            Name: Name,
            SeatNumber: SeatNumber,
          }),
        }
      );
      if (response.status !== 200) {
        throw new Error(
          `Area could not be updated or created (status ${response.status})`
        );
      }
      this.refreshAreas();
      return await response.json();
    } catch (e) {
      Messages.Show("is-warning", e.message);
      console.error(e);
      return;
    }
  }

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

  async refreshAreas() {
    this.areas = null;
    await this.getAreas();
  }
}