import { createTodosStore } from '$lib/stores/todo.js'

export const fieldsTeams = ["name", "color", "active", "external_id"];

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

    this.todos = createTodosStore(this);
  }

  update({ id, name, color, active, external_id }) {
    this.id = id;
    this.name = name;
    this.color = color;
    this.active = active;
    this.external_id = external_id;
  }

  toHexColor() {
    let num = this.color;
    num >>>= 0;
    let b = num & 0xFF,
	g = (num & 0xFF00) >>> 8,
	r = (num & 0xFF0000) >>> 16,
	a = ( (num & 0xFF000000) >>> 24 ) / 255 ;
    return "#" + r.toString(16) +  g.toString(16) +  b.toString(16);
  }
}

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

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