import {Image} from 'react-native';
import {ImageOrVideo} from 'react-native-image-crop-picker';
import {generateThumbnailUrl} from '@modules/chats/utils';

export const getImageDimensions = (
  uri: string,
  fallback?: {width?: number; height?: number},
): Promise<{width: number; height: number}> => {
  return new Promise(resolve => {
    Image.getSize(
      uri,
      (width, height) => resolve({width, height}),
      () =>
        resolve({
          width: fallback?.width || 1,
          height: fallback?.height || 1,
        }),
    );
  });
};

export const isImage = (file: ImageOrVideo) =>
  file.mime?.startsWith?.('image/');

export const isVideo = (file: ImageOrVideo) =>
  file.mime?.startsWith?.('video/');

export const generateAssetsThumbnails = async (
  assets: ImageOrVideo[],
  videoThumbs: Record<string, string>,
  onGenerate: (path: string, thumb: Nullable<string>) => void,
) => {
  for (const file of assets) {
    if (isVideo(file) && !videoThumbs[file.path]) {
      const thumb = await generateThumbnailUrl(file.path);
      onGenerate(file.path, thumb);
    }
  }
};
