// @flow

import type { MediaType } from '../types/media-types';

import fileType from 'file-type';

type FileInfo = {| name: string, mime: string, mediaType: MediaType |};
function fileInfoFromData(
  data: Uint8Array | Buffer,
  fileName: string,
): ?FileInfo {
  const fileTypeResult = fileType(data);
  if (!fileTypeResult) {
    return null;
  }
  const { ext, mime } = fileTypeResult;
  const mediaType = mimeTypesToMediaTypes[mime];
  if (!mediaType) {
    return null;
  }
  let [ readableFileName ] = fileName.split('.');
  if (!readableFileName) {
    readableFileName = Math.random().toString(36).slice(-5);
  }
  const maxReadableLength = 255 - ext.length - 1;
  const fixedFileName =
    `${readableFileName.substring(0, maxReadableLength)}.${ext}`;
  return { name: fixedFileName, mime, mediaType };
}

const mimeTypesToMediaTypes = {
  "image/png": "photo",
  "image/jpeg": "photo",
  "image/gif": "photo",
  "image/heic": "photo",
};

const extRegex = /\.([0-9a-z]+)$/i;
function extensionFromFilename(filename: string): ?string {
  const matches = filename.match(extRegex);
  if (!matches) {
    return null;
  }
  const match = matches[1];
  if (!match) {
    return null;
  }
  return match.toLowerCase();
}

const stripExtensionRegex = /(.*)\.[^.]+$/;
function stripExtension(filename: string): string {
  const matches = filename.match(stripExtensionRegex);
  if (!matches) {
    return filename;
  }
  return matches[1] ? matches[1] : filename;
}

const pathRegex = /^file:\/\/(.*)$/;
function pathFromURI(uri: string): ?string {
  const matches = uri.match(pathRegex);
  if (!matches) {
    return null;
  }
  return matches[1] ? matches[1] : null;
}

const filenameRegex = /[^/]+$/;
function filenameFromPathOrURI(pathOrURI: string): ?string {
  const matches = pathOrURI.match(filenameRegex);
  if (!matches) {
    return null;
  }
  return matches[0] ? matches[0] : null;
}

export {
  fileInfoFromData,
  mimeTypesToMediaTypes,
  extensionFromFilename,
  stripExtension,
  pathFromURI,
  filenameFromPathOrURI,
};

@@ -940,16 +940,70 @@
 photo%22,%0A
+  %22video/mp4%22: %22video%22,%0A  %22video/quicktime%22: %22video%22,%0A
 %7D;%0A%0Acons

Revert "[native] Temporarily disable video for new build"