export const fieldsExercices = ["title", "headline"];

export class Exercice {
  constructor(res) {
    if (res) {
      this.update(res);
    }
  }

  update({ id, id_theme, title, wip, urlid, path, statement, overview, headline, finished, issue, issuekind, depend, gain, coefficient, videoURI, resolution, seealso, forge_link }) {
    this.id = id;
    this.id_theme = id_theme;
    this.title = title;
    this.wip = wip
    this.urlid = urlid;
    this.path = path;
    this.statement = statement;
    this.overview = overview;
    this.headline = headline;
    this.finished = finished;
    this.issue = issue;
    this.issuekind = issuekind;
    this.depend = depend;
    this.gain = gain;
    this.coefficient = coefficient;
    this.videoURI = videoURI;
    this.resolution = resolution;
    this.seealso = seealso;
    this.forge_link = forge_link;
  }
}

export async function getExercices() {
  const res = await fetch(`api/exercices`, {headers: {'Accept': 'application/json'}})
  if (res.status == 200) {
    return (await res.json()).map((t) => new Exercice(t));
  } else {
    throw new Error((await res.json()).errmsg);
  }
}

export async function getThemedExercices(tid) {
  const res = await fetch(`api/themes/${tid}/exercices`, {headers: {'Accept': 'application/json'}})
  if (res.status == 200) {
    return (await res.json()).map((t) => new Exercice(t));
  } else {
    throw new Error((await res.json()).errmsg);
  }
}

export async function getExercice(eid) {
  const res = await fetch(`api/exercices/${eid}`, {headers: {'Accept': 'application/json'}})
  if (res.status == 200) {
    return new Exercice(await res.json());
  } else {
    throw new Error((await res.json()).errmsg);
  }
}

export async function getThemedExercice(tid, eid) {
  const res = await fetch(`api/themes/${tid}/exercices/${eid}`, {headers: {'Accept': 'application/json'}})
  if (res.status == 200) {
    return new Exercice(await res.json());
  } else {
    throw new Error((await res.json()).errmsg);
  }
}
