import fs from 'node:fs';
import path from 'node:path';

const STORE_PATH_NAME = 'store';
const TEMP_PATH_NAME = 'temp';

export function getResourcesDir() {
  return process.env.NODE_ENV === 'development'
    ? path.join(__dirname, '../../resources/')
    : path.join(__dirname, '../../../app.asar.unpacked/resources/');
}

export function getRootDir() {
  return process.env.NODE_ENV === 'development'
    ? path.join(__dirname, '../../')
    : path.join(__dirname, '../../../../');
}

export function getDatabasePath() {
  return path.join(getRootDir(), 'database', 'database.sqlite');
}

export function getStoreDir() {
  return path.join(getRootDir(), STORE_PATH_NAME);
}

export function getTempPath() {
  return path.join(getStoreDir(), TEMP_PATH_NAME);
}

export function getImagicPath() {
  return path.join(getResourcesDir(), './imagemagick/');
}

export function getGmFontPath() {
  // return path.join(getResourcesDir(), './font/STHeiti Medium.ttc');
  return path.join(getResourcesDir(), './font/simsun.ttf');
}

export function makeDirSync(pathContent: string) {
  const mkPathList: string[] = [];
  let curPath = pathContent;

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

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

makeDirSync(getTempPath());

// 系统配置
interface ConfigSetType {
  downloadProcessCount: number;
}
type PartConfigSetType = Partial<ConfigSetType>;
type ConfigSetTypeEnum = keyof ConfigSetType;

const configSets = [
  {
    field: 'downloadProcessCount',
    validate(val: any) {
      return [1, 2, 3].includes(val);
    },
    default: 1,
  },
];

function getConfig(datas: PartConfigSetType) {
  const configData = {} as ConfigSetType;
  configSets.forEach((config) => {
    const field = config.field as ConfigSetTypeEnum;
    if (config.validate(datas[field])) {
      configData[field] = datas[field] as ConfigSetType[ConfigSetTypeEnum];
    } else {
      configData[field] = config.default;
    }
  });
  return configData;
}

export function getConfigData(data: PartConfigSetType) {
  let configData = getConfig(data);
  if (process.env.NODE_ENV === 'development') return configData;

  const configPath = path.join(getRootDir(), 'config.json');
  if (fs.existsSync(configPath)) {
    try {
      const configFileData = JSON.parse(
        fs.readFileSync(configPath, 'utf8')
      ) as PartConfigSetType;
      configData = getConfig(configFileData);
    } catch (error) {
      console.log(error);
    }
  }

  return configData;
}
