
import { Lab, sRGB } from "../color/color";
import { ColorInfo, ColorMap, ColorSumItem } from "./interfaces";
import { Neigbours, simpleMerge } from "./kmeans";

export function colorDistance(a: ColorSumItem, b: ColorSumItem): number {
  return Math.abs(a.lab.deltaE(b.lab));
}


/**
 * Convert colorMap to color list.
 * @param colorMap 
 * @returns 
 */
export function colorMapToColorSum(colorMap: ColorMap): ColorSumItem[] {
  let sumHash = {};
  Object.keys(colorMap).forEach(_areaIndex => {
    let areaIndex = parseInt(_areaIndex);
    let { color, cssColor } = colorMap[areaIndex];
    if (sumHash[color]) {
      sumHash[color].total++;
      sumHash[color].areas.push(areaIndex);
    } else {
      sumHash[color] = {
        cssColor,
        color,
        total: 1,
        lab: Lab.fromRGBA(color),
        areas: [areaIndex],
      }
    }
  })

  return Object.values(sumHash);
}

/**
 * 根据最小颜色距离合并colorMap
 * @param input  输入colorMap
 * @param minDist  最小颜色距离
 * @returns  颜色合并后的 colorMap
 */
export function mergeByColorMap(input: ColorMap, minDist: number = 4): ColorMap {
  let dataset: ColorSumItem[] = colorMapToColorSum(input);
  let result: Neigbours<ColorSumItem>[] = simpleMerge(dataset, minDist, colorDistance);

  let colorMap = {};
  result.forEach(nei => {
    let color = nei.self.color;
    let cssColor = nei.self.cssColor;
    let colorInfo: ColorInfo = { color, cssColor };
    nei.neigbours.forEach(item => {
      item.areas.forEach(area => {
        colorMap[area] = colorInfo;
      })
    })
  })

  return colorMap;
}



