const path = require('path')
const fs = require('fs')
const recursive = require('recursive-readdir')
const importer = require('./importer')

const args = process.argv.slice(2)
// 要处理的目录
let dir = args[0]
if (dir === '$PWD') dir = args[1]
const workspace = path.resolve(process.cwd(), '..')

// 删除多余的自动导入文件
recursive(
  dir,
  [
    (file, stats) => {
      return (
        stats.isFile() &&
        !(path.dirname(file).endsWith('_import-components') && file.endsWith('-import.js'))
      )
    },
  ],
  function(_err, files) {
    files.forEach((file) => {
      const vueFile = file
        .replace('_import-components' + path.sep, '')
        .replace('-import.js', '.vue')
      if (!fs.existsSync(vueFile)) {
        // eslint-disable-next-line no-console
        console.log('delete unused file: ' + file)
        fs.unlinkSync(file)
      }
    })
  }
)

// 更新自动导入文件
recursive(
  dir,
  [
    (file, stats) => {
      return stats.isFile() && path.extname(file) !== '.vue'
    },
  ],
  function(_err, files) {
    files.forEach((file) => {
      importer(file, workspace)
    })
  }
)
