import * as mimeTypes from 'mime-types';
import {getTextMetadata, TextMetadata} from '@modal-soft/text-utils';
import {getImageMetadata, ImageMetadata} from '@modal-soft/image-utils';
import {getAudioMetadata, AudioMetadata} from '@modal-soft/audio-utils';
import {getVideoMetadata, VideoFileMetadata} from '@modal-soft/video-utils';

const MIME_TYPE_DESCRIPTIONS = {
  'image/gif': 'GIF Image',
  'image/jpeg': 'JPEG Image',
  'image/png': 'PNG Image',
  'image/tiff': 'TIFF Image',
  'image/svg+xml': 'SVG Image',
  'audio/wav': 'WAVE Audio',
  'audio/ogg': 'OGG Audio',
  'audio/mpeg': 'MPEG Audio',
  'audio/mid': 'MIDI Track',
  'application/json': 'JSON Data',
  'application/xml': 'XML Data',
  'application/x-bittorrent': 'Torrent File',
  'application/x-zip-compressed': 'Compressed ZIP Archive',
  'application/x-x509-ca-cert': 'Certificate File',
  'application/x-tar': 'Compressed TAR Archive',
  'application/x-rar': 'Compressed RAR Archive',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'Workbook',
  'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'Slideshow Presentation',
  'application/msword': 'Microsoft Word Document',
  'application/pdf': 'PDF Document',
  'application/postscript': 'PostScript Document',
  'application/epub+zip': 'EPUB Document',
  'message/rfc822': 'Email Message',
  'video/mp4': 'MP4 Video',
} as const;

const EXTENSION_DESCRIPTIONS = {
  'rar': 'Compressed RAR Archive',
  '7z': 'Compressed 7-Zip Archive',
  'psd': 'Adobe Photoshop Document',
  'dmg': 'Disk Image',
  'fb2k-component': 'foobar2000 Component',
} as const;

export const getMimeTypeDescription = (type?: string, filename?: string) => {
  if (typeof (type as unknown) !== 'string') {
    return '';
  }

  if (type === 'application/octet-stream' || type === '') {
    if (typeof filename === 'string' && filename.includes('.')) {
      const extension = filename.slice(filename.lastIndexOf('.') + '.'.length).toLowerCase();
      const {
        [extension as keyof typeof EXTENSION_DESCRIPTIONS]: extensionDescription = `${extension.toUpperCase()} File`,
      } = EXTENSION_DESCRIPTIONS;

      return extensionDescription;
    }
    return `${type} File`;
  }

  const {
    [type as keyof typeof MIME_TYPE_DESCRIPTIONS]: description = type,
  } = MIME_TYPE_DESCRIPTIONS;

  return description;
}

export enum ContentType {
  TEXT = 'text',
  AUDIO = 'audio',
  VIDEO = 'video',
  IMAGE = 'image',
  BINARY = 'binary',
}

export const getContentType = (mimeType?: string, filename?: string) => {
  let effectiveMimeType: string;
  if (typeof mimeType !== 'string') {
    if (typeof filename !== 'string') {
      return ContentType.BINARY;
    }
    const lookupMimeType = mimeTypes.lookup(filename);

    if (typeof lookupMimeType !== 'string') {
      return ContentType.BINARY;
    }

    effectiveMimeType = lookupMimeType;
  } else {
    effectiveMimeType = mimeType;
  }

  if (
    effectiveMimeType === 'application/json'
    || effectiveMimeType === 'application/xml'
    || effectiveMimeType.startsWith('text/')
  ) {
    return ContentType.TEXT;
  }

  if (effectiveMimeType.startsWith('video/')) {
    return ContentType.VIDEO;
  }

  if (effectiveMimeType.startsWith('audio/')) {
    return ContentType.AUDIO;
  }

  if (effectiveMimeType.startsWith('image/')) {
    return ContentType.IMAGE;
  }

  return ContentType.BINARY;
}

export const readAsDataURL = (blob: Partial<Blob>) => new Promise<string>((resolve, reject) => {
  const reader = new FileReader();
  reader.addEventListener('error', () => {
    reject(new Error('Could not read file as data URL'));
  });

  reader.addEventListener('load', (e) => {
    if (!e.target) {
      reject();
      return;
    }
    resolve(e.target.result as string);
  });

  reader.readAsDataURL(blob as Blob);
});

export interface FileWithDataUrl extends File {
  url?: string;
}

export const addDataUrl = async (f: Partial<File>): Promise<Partial<FileWithDataUrl>> => {
  (f as unknown as Record<string, unknown>).url = await readAsDataURL(f);
  return f;
}

export interface FileWithResolvedContentType extends Partial<FileWithDataUrl> {
  resolvedType: ContentType;
}

export interface TextFile extends FileWithResolvedContentType {
  resolvedType: ContentType.TEXT;
  metadata?: TextMetadata;
}

export const augmentTextFile = async <T extends Partial<FileWithDataUrl>>(file: T): Promise<TextFile> => {
  const contents = typeof file?.text === 'function' ? await file.text() : '';
  const fileMutable = file as unknown as Record<string, TextMetadata>;
  fileMutable.metadata = await getTextMetadata(contents ?? '', file.name);
  return fileMutable as unknown as TextFile;
};

export interface ImageFile extends FileWithResolvedContentType {
  resolvedType: ContentType.IMAGE;
  metadata?: ImageMetadata;
}

export const augmentImageFile = async <T extends Partial<FileWithDataUrl>>(file: T): Promise<ImageFile> => {
  const fileMutable = file as unknown as Record<string, ImageMetadata>;
  fileMutable.metadata = await getImageMetadata(file.url);
  return fileMutable as unknown as ImageFile;
};

export interface AudioFile extends FileWithResolvedContentType {
  resolvedType: ContentType.AUDIO;
  metadata?: AudioMetadata;
}

export const augmentAudioFile = async <T extends Partial<FileWithDataUrl>>(file: T): Promise<AudioFile> => {
  const fileMutable = file as unknown as Record<string, AudioMetadata>;
  fileMutable.metadata = await getAudioMetadata(file.url, file.type);
  return fileMutable as unknown as AudioFile;
};

export interface BinaryFileMetadata {
  contents: ArrayBuffer;
}

export interface BinaryFile extends FileWithResolvedContentType {
  resolvedType: ContentType.BINARY;
  metadata?: BinaryFileMetadata;
}

export const augmentBinaryFile = async <T extends Partial<FileWithDataUrl>>(file: T): Promise<BinaryFile> => {
  const metadata = {} as BinaryFileMetadata;
  if (typeof file?.arrayBuffer === 'function') {
    metadata.contents = await file.arrayBuffer();
  }
  const fileMutable = file as unknown as Record<string, BinaryFileMetadata>;
  fileMutable.metadata = metadata;
  return fileMutable as unknown as BinaryFile;
};

export interface VideoFile extends FileWithResolvedContentType {
  resolvedType: ContentType.VIDEO;
  metadata?: VideoFileMetadata;
}

export const augmentVideoFile = async <T extends Partial<FileWithDataUrl>>(file: T): Promise<VideoFile> => {
  const fileMutable = file as unknown as Record<string, AudioMetadata>;
  fileMutable.metadata = await getVideoMetadata(file.url);
  return fileMutable as unknown as VideoFile;
};
