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

// SsdMobilenetv1Options
export const minConfidence = 0.4;

// TinyFaceDetectorOptions
export const inputSize = 416;
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 const saveFile = async (
  basePath: string,
  fileName: string,
  buf: Buffer
): Promise<void> => {
  return new Promise(async (resolve, reject) => {
    try {
      //Create directory if it does not exist
      await makeDirectory(basePath);
    } catch (err) {
      return reject(err);
    }
    //Write file to directory
    try {
      const asdf = fs.writeFileSync(
        path.join(basePath, fileName),
        buf,
        "base64"
      );
    } catch (err) {
      return reject(err);
    }

    return resolve();
  });
};

export const makeDirectory = (path: string): Promise<void> => {
  return new Promise(async (resolve, reject) => {
    if (!fs.existsSync(path)) {
      fs.mkdir(path, async (err) => {
        if (err) {
          return reject(err);
        }

        return resolve();
      });
    }

    return resolve();
  });
};

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