import * as mimeTypes from 'mime-types';

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;
};
