
export default class RandomColor {

  private countPerChannel: number;
  private numberArray: Array<number>;

  constructor(count: number, extcolors: number[] = []) {
    this.countPerChannel = Math.ceil(Math.cbrt(count));
    let colors = Math.pow(this.countPerChannel, 3);
    let colorsArray = new Uint32Array(colors);
    let bytesArray = new Uint8Array(colorsArray.buffer);

    let stepPerChannel = this.countPerChannel - 1;

    var index = 0;
    for (var r = 0; r <= stepPerChannel; r++) {
      var rr = Math.round((r * 255) / stepPerChannel);
      for (var g = 0; g <= stepPerChannel; g++) {
        var gg = Math.round((g * 255) / stepPerChannel);
        for (var b = 0; b <= stepPerChannel; b++) {
          var bb = Math.round((b * 255) / stepPerChannel);
          bytesArray[index * 4 + 0] = rr;
          bytesArray[index * 4 + 1] = gg;
          bytesArray[index * 4 + 2] = bb;
          bytesArray[index * 4 + 3] = 255;
          index++;
        }
      }
    }

    this.numberArray = new Array(colors);
    for (var i = 0; i < colorsArray.length; i++) {
      this.numberArray[i] = colorsArray[i];
    }

    for (let extcolor of extcolors) {
      let index = this.numberArray.findIndex(e => e == extcolor);
      if (index >= 0) {
        this.numberArray.splice(index, 1);
      }
    }

    console.log(this.numberArray.length, this.numberArray);
  }

  get() {
    var index = Math.floor(Math.random() * this.numberArray.length);
    var color = this.numberArray.splice(index, 1);
    return color[0];
  }

  checkDistance() {
    const size = this.numberArray.length;
    var dist;
    var minDist = 1000;
    for (var x = 0; x < size; x++) {
      for (var y = x + 1; y < size; y++) {
        dist = this.distance(this.numberArray[x], this.numberArray[y]);
        if (dist < minDist) {
          minDist = dist;
        }
      }
    }
    console.log(`minDist=${minDist}`);
  }


  distance(c1: number, c2: number, debug: boolean = false): number {
    let a1 = (c1 >> 24) & 0xff;
    let b1 = (c1 >> 16) & 0xff;
    let g1 = (c1 >> 8) & 0xff;
    let r1 = c1 & 0xff;

    let a2 = (c2 >> 24) & 0xff;
    let b2 = (c2 >> 16) & 0xff;
    let g2 = (c2 >> 8) & 0xff;
    let r2 = c2 & 0xff;

    let rr = r1 - r2;
    let gg = g1 - g2;
    let bb = b1 - b2;

    let dist = Math.sqrt(rr * rr + gg * gg + bb * bb) / 255;

    if (debug) {
      console.log(`${c1}, ${c2}, dist:${dist}`);
      console.log(r1, g1, b1, a1);
      console.log(r2, g2, b2, a2);
    }

    return dist;
  }
}

// //至少3000个颜色
// let rand = new RandomColor(9000);
// rand.checkDistance();

// var c1 = rand.get();
// var c2 = rand.get();
// rand.distance(c1, c2, true)


