import * as sizeOf from 'image-size';
import { fs, fsPath } from '../common';
import * as types from './types';

/**
 * Converts the given image to a data structure, including size.
 */
export async function toManifestImage(
  filePath: string,
  urlPath: string,
  options: { size?: boolean } = {},
) {
  const parts = fsPath.parse(filePath);
  const dir = parts.dir;
  const name = parts.name.replace(/\@2x$/, '');
  const ext = parts.ext.replace(/^\./, '');

  const image: types.IManifestImage = {
    type: 'FILE/image',
    name,
    ext,
    path: urlPath,
  };

  const file1x = fsPath.join(dir, parts.base);
  if (!(await fs.pathExists(file1x))) {
    return;
  }

  if (!is2x(filePath)) {
    const name2x = `${image.name}@2x.${image.ext}`;
    const file2x = fsPath.join(dir, name2x);
    if (await fs.pathExists(file2x)) {
      image.path2x = fsPath.join(fsPath.dirname(urlPath), name2x);
    }
  }

  if (options.size === true) {
    const { width, height } = await getSize(file1x);
    image.width = width;
    image.height = height;
  }

  return image;
}

/**
 * INTERNAL
 */
const is2x = (value: string) => value.includes('@2x');

async function getSize(path: string) {
  return new Promise<{ width: number; height: number }>((resolve, reject) => {
    sizeOf(path, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}
