/**
 * 文件相关操作在这里维护
 */
import path from 'path'
import fs from 'fs'
import chalk from 'chalk'
import ejs from 'ejs'
const fsEx = require('fs-extra')

/**
 * 动态渲染文件内容并写入到某文件
 * @param {string} src 模板绝对路径
 * @param {string} dist 写入到绝对路径
 * @param {object} data 模板参数
 * @returns
 */
export function ejsWriteFile(src: string, dist: string, data: object) {
  return new Promise((resolve) => {
    ejs.renderFile(src, data, {}, (err: any, res: any) => {
      if (err) {
        console.log(chalk.red(`${err}`))
        resolve(false)
        return
      }
      fsEx.writeFileSync(dist, res)
      resolve(true)
    })
  })
}

// 判断是否是个目录
export function isDirectory(path: string) {
  return fs.statSync(path).isDirectory()
}

export function getPackageInfo() {
  const packagePath =  path.resolve(process.cwd(), './package.json')
  if (!fsEx.pathExistsSync(packagePath)) {
    throw new Error(chalk.red(`error: 当前路径不存在package.json`));
  }
  const json = fs.readFileSync(packagePath).toString()
  return JSON.parse(json)
}

export default {
  ejsWriteFile,
  isDirectory,
  getPackageInfo
}
