import path from 'path'
import fs from'fs'
import serialize from'serialize-javascript'
import chalk from 'chalk'
import { beautifyJs } from './beautify-file'
import { formatPath } from './other'
import { ejsWriteFile } from './file'
import {
  PROJECT_DOC_CONFIG_PATH,
  DEFAULT_STORYBOOK_CONFIG_PATH,
  STORYBOOK_CONFIG_PATH,
  DEFAULT_STORYBOOK_WEBPACK_PATH,
  STORYBOOK_WEBPACK_PATH,
  DOC_ROOT_PATH
} from'../constant/doc'
const fsEx = require('fs-extra')

// 获取storybook配置
/**
 *
 * @param {String} fileName 文件名称，含后缀
 * @param {String} readWay 读取方式。require:require用读取,read:通过read方式读取
 * @returns
 */
 export function getDocConfig(fileName: string, readWay: string) {
  let projectConfig
  let defaultConfig

  // 获取项目storybook配置
  const projectConfigPath = path.join(PROJECT_DOC_CONFIG_PATH, fileName)
  // 获取默认的storybook配置
  const defaultConfigPath = path.join(DEFAULT_STORYBOOK_CONFIG_PATH, fileName)

  if (process.env.debug) {
    console.log(
      chalk.yellow(
        `debug:项目路径${projectConfigPath}是否存在: ${fs.existsSync(
          projectConfigPath
        )}`
      )
    )
    console.log(
      chalk.yellow(
        `debug:默认路径${defaultConfigPath}是否存在: ${fs.existsSync(
          defaultConfigPath
        )}`
      )
    )
  }

  // 没有文件则自动创建
  fsEx.ensureFileSync(defaultConfigPath)

  if (readWay === 'require') {
    projectConfig = require(projectConfigPath)
    defaultConfig = require(defaultConfigPath)
  } else {
    projectConfig = fs.readFileSync(projectConfigPath).toString()
    defaultConfig = fs.readFileSync(defaultConfigPath).toString()
  }
  if (projectConfig.stories) {
    const stories = projectConfig.stories.reduce((arr: Array<any>, item: any) => {
      arr.push(formatPath(item))
      return arr
    }, [])
    projectConfig.stories = stories
  }

  return {
    defaultConfig,
    projectConfig,
  }
}

// 合并main.js配置
export function mergeMainJs(fileName:string) {
  const config = getDocConfig(fileName, 'require')
  const defaultConfig = config.defaultConfig
  const projectConfig = config.projectConfig
  const newConfig = Object.assign(defaultConfig, projectConfig)

  // 调试
  process.env.debug &&
    console.log(
      chalk.yellow(`debug:main.js配置 ${JSON.stringify(newConfig, null, 2)})}`)
    )

  const targetConfigPath = path.join(STORYBOOK_CONFIG_PATH, fileName)
  const data = beautifyJs(
    `module.exports = ${serialize(newConfig, {
      unsafe: true,
    })}`
  )
  fsEx.outputFileSync(targetConfigPath, data)
}

// 重写storybook配置文件
export function overwriteConfig(fileName:string) {
  const { projectConfig } = getDocConfig(fileName, 'read') || {}

  // 调试
  process.env.debug &&
    console.log(chalk.yellow(`debug:${fileName}配置`))

  const targetConfigPath = path.join(STORYBOOK_CONFIG_PATH, fileName)
  if (projectConfig) {
    fsEx.outputFileSync(targetConfigPath, projectConfig)
  }
}

// 动态生成webpack配置
export function generateWebpack() {
  const projectWebpackPath = formatPath(path.join(
    PROJECT_DOC_CONFIG_PATH,
    'webpack.config.js'
  ))

  // 读取项目组的webpack
  const projectWebpack = beautifyJs(
    `const webpack = require('${projectWebpackPath}')
    await webpack({config, mode})`
  )


  ejsWriteFile(DEFAULT_STORYBOOK_WEBPACK_PATH, STORYBOOK_WEBPACK_PATH, {
    ROOT_PATH: formatPath(process.cwd()), // 约定指令要在根目录执行，所以这里指的就是项目根路径
    WEBPACK: projectWebpack,
  })
}

// 合并storybook配置
export function mergeConfig() {
  if (!fsEx.pathExistsSync(DOC_ROOT_PATH)) {
    console.log(chalk.red('脚手架内置文档文件不存在，请重新执行ark generate --doc进行安装'))
    return
  }
  // 合并main.js配置
  mergeMainJs('main.js')
  // 根据项目路径生成webpack配置
  generateWebpack()
  // 复制preview.js到脚手架
  overwriteConfig('preview.js')
  // 复制preview-head.html
  overwriteConfig('preview-head.html')
  // 复制preview-body.html
  overwriteConfig('preview-body.html')
  // 复制middleware.js
  // overwriteConfig('middleware.js') // 暂时去掉中间件代理功能。因为没人用
}

export default {
  mergeConfig,
}
