/* eslint-disable @lwc/lwc/no-async-await */
const path = require('path')
const fs = require('fs')
const compiler = require('vue/compiler-sfc')
const { minify } = require('terser')

const terserOptions = {
  compress: {
    defaults: false,
  },
}

const builderDir = path.join(process.cwd(), 'src', 'form-designer')
fs.readdirSync(builderDir, { withFileTypes: true }).forEach((dirent) => {
  if (
    dirent.isFile() &&
    !['index.js', 'index-normalize-route.js'].includes(dirent.name)
    // &&dirent.name === 'util.js'
    // &&dirent.name === 'sd-default-value.vue'
  ) {
    const file = path.join(builderDir, dirent.name)
    if (dirent.name.endsWith('.vue')) {
      processVue(file)
    } else if (dirent.name.endsWith('.js')) {
      processJS(file)
    }
  }
})

function logError(error) {
  const { message } = error
  if (message !== 'Unexpected token: operator (<)') {
    // jsx导致的报错不提示
    console.log(path, error)
  }
}

async function processJS(path) {
  const content = fs.readFileSync(path).toString()
  try {
    const result = await minify(content, terserOptions)
    writeFile(path, '/* eslint-disable */\n' + result.code)
  } catch (error) {
    logError(error)
  }
}

async function processVue(path) {
  const content = fs.readFileSync(path).toString()

  // const resultx = compiler.parseComponent(content)
  // const template = result.template
  // const render = compiler.compileToFunctions(template.content)

  // const parseResult = utils.parse({ source: content, compiler, needMap: false })

  const parseResult = compiler.parseComponent(content)
  if (!parseResult.template) return

  const template = parseResult.template.content
  const render = compiler.compileTemplate({ source: template, filename: path }).code

  let script = parseResult.script.content
  // 压缩 js
  try {
    const minifyResult = await minify(script, terserOptions)
    script = minifyResult.code
  } catch (error) {
    logError(error)
  }

  // 加上 render
  script = script.replace(/export default ?{/, render + '\nexport default {\n  render,')

  let result = content.replace(/<template>[\s\S]*<\/template>/, '')

  result = result.replace(
    /<script>[\s\S]*<\/script>/,
    '<script>\n/* eslint-disable */\n// sd-skip-auto-import\n' + script + '\n</script>'
  )

  writeFile(path, result)
}

function writeFile(jsFile, jsContent) {
  // 生成最终的js文件
  fs.writeFile(jsFile, jsContent, (error) => {
    if (error) {
      // eslint-disable-next-line no-console
      console.error('Error while creating ' + jsFile)
      throw error
    }
  })
}
