const path = require("path");
const fs = require("fs");
const homePath = path.dirname(process.execPath);
const storePath = path.join(homePath, "stores");
const extraPath =
  process.env.NODE_ENV === "production"
    ? path.join(homePath, "extra")
    : path.join(__static, "../extra");

initPath();
function initPath() {
  const paths = [
    storePath,
    getInputDir(),
    getStoresDir("out"),
    getOutputDir("origin")
  ];
  paths.forEach(path => {
    if (!fs.existsSync(path)) fs.mkdirSync(path);
  });
}
// base
function getHomeDir(name) {
  return path.join(homePath, name);
}

function getStoresDir(name) {
  return path.join(storePath, name);
}

function getExtraDir(name) {
  return path.join(extraPath, name);
}

// stores
function getInputDir() {
  return getStoresDir("in");
}
function getOutputDir(type) {
  return path.join(getStoresDir("out"), type);
}
function getTmpDir() {
  return getStoresDir("tmp");
}

// extra
function getDatabaseDir() {
  return getExtraDir("database");
}

function getScanExePath() {
  return path.join(extraPath, "scan", "scan.exe");
}

/**
 *
 * @param {String} pathContent 目录路径
 */
function makeDirSync(pathContent) {
  let mkPathList = [];
  let curPath = pathContent;

  while (!fs.existsSync(curPath)) {
    mkPathList.unshift(curPath);
    curPath = path.dirname(curPath);
  }

  mkPathList.forEach(path => {
    fs.mkdirSync(path);
  });
}

// function formatNum(num, [min, max]) {
//   return !num || num > max || num < min ? max : num;
// }

function initConfigData(data) {
  let configData = { ...data };
  if (!configData.input) configData.input = getInputDir();

  if (process.env.NODE_ENV === "development") return configData;

  const configPath = path.join(homePath, "config.json");
  if (fs.existsSync(configPath)) {
    configData = JSON.parse(fs.readFileSync(configPath, "utf8"));
    if (!configData.input) configData.input = getInputDir();
  } else {
    fs.writeFileSync(configPath, JSON.stringify(configData), "utf8");
  }

  return configData;
}

export {
  initPath,
  getHomeDir,
  getStoresDir,
  getExtraDir,
  getInputDir,
  getOutputDir,
  getScanExePath,
  getTmpDir,
  makeDirSync,
  getDatabaseDir,
  initConfigData
};
