import ColorThief from 'colorthief';

export const getImageMetadata = (imageUrl: string) => new Promise<Record<string, string | number | [number, number, number][]>>((resolve, reject) => {
  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();
  });

  image.src = imageUrl;
});
