import { promisify } from "util";
import { readFile } from "fs";
import { join } from "path";
import { getDate } from "taehui-ts/date";

import Configure from "src/system/Configure";
import DB from "src/system/DB";
import { isBannedIP } from "src/Utility";

const rf = promisify(readFile);

export const getFile = async (fileName: string, avatarIP: string) => {
  return (
    await Promise.all([
      isBannedIP(avatarIP) ||
      fileName.match(/^.*\.(bmp|gif|jpeg|jpg|png|webp)$/i) ||
      fileName.match(
        /^.*\.(aif|aiff|asf|flac|m4a|mid|midi|mp2|mp3|ogg|opus|raw|wav|wma)$/i,
      ) ||
      fileName.match(/^.*\.(avi|flv|m1v|mkv|mov|mp4|mpeg|mpg|webm|wmv)$/i)
        ? Promise.resolve()
        : DB.postFileHit(fileName, avatarIP, getDate()),
      rf(join(Configure.path.essay, fileName)),
    ])
  )[1];
};

export const getPostedFileName = async (fileName: string) => {
  return DB.getPostedFileName(fileName);
};

export const getFileHit = async (fileName: string) => {
  return DB.getFileHit(fileName);
};
