import hsv2rgb from 'hsv2rgb';
import {Injectable} from '@angular/core';

import {perc2color} from '../app.config';

@Injectable({providedIn: 'root'})
export class AdjusterLegendService {
  /** https://colorbrewer2.org/?type=qualitative&scheme=Paired&n=12 */
  colorPalette = [
    '#a6cee3',
    '#1f78b4',
    '#b2df8a',
    '#33a02c',
    '#fb9a99',
    '#e31a1c',
    '#fdbf6f',
    '#ff7f00',
    '#cab2d6',
    '#6a3d9a',
    '#ffff99',
    '#b15928',
  ];
  constructor() {}

  createIndexLegend(): FakeLegend {
    return [
      {color: perc2color(0), name: '0 %'},
      {color: perc2color(0.25), name: '25 %'},
      {color: perc2color(0.5), name: '50 %'},
      {color: perc2color(0.75), name: '75 %'},
      {color: perc2color(1), name: '100 %'},
    ];
  }

  createClusterLegend(count: number): FakeLegend {
    const legend = [];
    let i = 0;
    while (i < count) {
      legend.push({color: this.colorPalette[i], name: `Cluster ${i + 1}`});
      i++;
    }
    return legend;
  }

  refreshColorPalette(count: number): void {
    this.colorPalette = this.generateRandomColorPalette(count);
  }

  /**
   * https://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
   * @private
   * @description Only generates random colors if the current palette does not provide enough colors for all the clusters
   * @param {number} colorCount Number of colors to randomly generate
   * @returns {Array<Array<number> | string>} Array of RGB colors
   */
  private generateRandomColorPalette(colorCount: number): Array<string> {
    const palette = this.colorPalette;
    const goldenRatioConjugate = 0.618033988749895;
    let i = palette.length;
    while (i < colorCount) {
      let h = Math.random();
      h += goldenRatioConjugate;
      h %= 1;
      h *= 360;
      palette.push(hsv2rgb(h, 0.5, 0.95));
      i++;
    }
    return palette;
    //return `rgba(${r}, ${g}, ${b}, 0.7)`;
  }
}

type FakeLegend = Array<{
  color: string;
  name: string;
}>;
