import * as faceapi from "@vladmandic/face-api";
import * as path from "path";
import fs from "fs";

// SsdMobilenetv1Options
export const minConfidence = 0.5;

// TinyFaceDetectorOptions
export const inputSize = 408;
export const scoreThreshold = 0.5;

export const getFaceDetectorOptions = (net: faceapi.NeuralNetwork<any>) => {
  return net === faceapi.nets.ssdMobilenetv1
    ? new faceapi.SsdMobilenetv1Options({ minConfidence })
    : new faceapi.TinyFaceDetectorOptions({ inputSize, scoreThreshold });
};

export function saveFile(
  basePath: string,
  fileName: string,
  buf: Buffer
): Promise<void> {
  const writeFile = (): Promise<void> => {
    return new Promise((resolve, reject) => {
      fs.writeFile(path.resolve(basePath, fileName), buf, "base64", (err) => {
        if (err) {
          return reject(err);
        }
        resolve();
      });
    });
  };
  return new Promise(async (resolve, reject) => {
    if (!fs.existsSync(basePath)) {
      fs.mkdir(basePath, async (err) => {
        if (err) {
          return reject(err);
        }
        resolve(await writeFile());
      });
    } else {
      resolve(await writeFile());
    }
  });
}

export const delay = (ms: number): Promise<void> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, ms);
  });
};
