import ColorThief from 'colorthief';
import {DEFAULT_PALETTE_COLOR_COUNT, GetImageMetadataOptions, ImageMetadata} from './common';

const doGetImageMetadata = async (thisImage: HTMLImageElement, options = {} as GetImageMetadataOptions): Promise<Partial<ImageMetadata>> => {
  const { paletteColorCount = DEFAULT_PALETTE_COLOR_COUNT } = options;
  const colorThief = new ColorThief();
  const palette = await colorThief.getPalette(thisImage, paletteColorCount);
  return {
    width: thisImage.naturalWidth,
    height: thisImage.naturalHeight,
    palette,
  };
};

export const getMetadataFromElement = (thisImage: HTMLImageElement, options?: GetImageMetadataOptions): Promise<Partial<ImageMetadata>> => doGetImageMetadata(thisImage, options);

export const getMetadataFromUrl = (imageUrl: string, options = {} as GetImageMetadataOptions): Promise<Partial<ImageMetadata>> => new Promise((resolve, reject) => {
  const image = new Image();

  image.addEventListener('load', async (imageLoadEvent) => {
    const thisImage = imageLoadEvent.currentTarget as HTMLImageElement;
    const metadata = await doGetImageMetadata(thisImage, options);
    image.remove();
    resolve(metadata);
  });

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

  image.src = imageUrl;
});
