import ColorThief from 'colorthief';

type RgbTuple = [number, number, number];

export interface ImageMetadata {
  width?: number;
  height?: number;
  palette?: RgbTuple[];
}

export const getImageMetadata = (imageUrl?: string) => new Promise<ImageMetadata>((resolve, reject) => {
  // TODO server side
  const image = new Image();

  image.addEventListener('load', async (imageLoadEvent) => {
    const thisImage = imageLoadEvent.currentTarget as HTMLImageElement;
    const colorThief = new ColorThief();
    const palette = await colorThief.getPalette(thisImage, 8);
    const metadata = {
      width: thisImage.naturalWidth,
      height: thisImage.naturalHeight,
      palette,
    };
    image.remove();
    resolve(metadata);
  });

  image.addEventListener('error', () => {
    reject(new Error('Could not load file as image'));
    image.remove();
  });

  if (imageUrl === undefined) {
    resolve({});
    return;
  }

  image.src = imageUrl;
});
