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

const doGetImageMetadata = async (input: string | Buffer, options = {} as GetImageMetadataOptions): Promise<Partial<ImageMetadata>> => {
  const { paletteColorCount = DEFAULT_PALETTE_COLOR_COUNT } = options;
  const { imageSize, disableFS } = await import('image-size');
  disableFS(true);
  const { default: getColors } = await import('get-image-colors');
  const dimensions = imageSize(input);
  const palette = await getColors(input, { count: paletteColorCount });
  return {
    width: dimensions.width,
    height: dimensions.height,
    palette: palette.map((color) => color.rgb()),
  };
};

export const getMetadataFromUrl = (imageUrl: string, options?: GetImageMetadataOptions): Promise<Partial<ImageMetadata>> => doGetImageMetadata(imageUrl, options);

export const getMetadataFromBuffer = (buffer: Buffer, options?: GetImageMetadataOptions): Promise<Partial<ImageMetadata>> => doGetImageMetadata(buffer, options);
