const colorPalette = [
  '#FF0000', '#FFA500', '#FFFF00', '#00FF00', '#008000', '#0000FF',
  '#000080', '#800080', '#FF00FF', '#FFC0CB', '#00FFFF', '#008080',
];

/**
 * @template T
 * @param {T[]} array
 * @param {(item: T) => unknown} key
 * @returns {T}
 */
function min(array, key=x => x) {
  return array.reduce((prev, curr) => key(curr) < key(prev) ? curr : prev);
}

export class ResourceColorPalette {
  /**
   * @type {{ resource: import(
   *   '../../../../../../composables/resourcestore'
   * ).Resource, color: string }[]}
   */
 #resourcesAndColors;

  get resourcesAndColors() { return this.#resourcesAndColors; }

  constructor() {
    this.#resourcesAndColors = [];
  }

  /**
   * @param {import('../../../../../../composables/resourcestore').Resource[
   * ]} resources
   */
  update(resources) {
    const resourceIDToColor = new Map(this.#resourcesAndColors.map(
      x => [x.resource.id, x.color]
    ));
    const colors = resources.map(x => resourceIDToColor.get(x.id));
    const usedColorCounts = new Map(colorPalette.map(x => [x, 0]));
    for(const color of colors.filter(x => x != null)) {
      usedColorCounts.set(color, usedColorCounts.get(color) + 1);
    }

    for(const idx of colors.map((x, i) => [i, x]).filter(
      x => x[1] == null
    ).map(x => x[0])) {
      colors[idx] = min([...usedColorCounts.entries()], x => x[1])[0];
      usedColorCounts.set(colors[idx], usedColorCounts.get(colors[idx]) + 1);
    }

    this.#resourcesAndColors = resources.map((x, i) => ({
      resource: x, color: colors[i],
    }));
  }
}
