const path = require('path')
const fs = require('fs')

// webpack.config.js
const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { ElementPlusResolver } = require('unplugin-vue-components/resolvers')
const CopyWebpackPlugin = require('copy-webpack-plugin');


// Generate pages object
const pages = {}

function getEntryFile(entryPath) {
  let files = fs.readdirSync(entryPath)
  return files
}

// const logoName = getEntryFile(path.resolve(`src/assets/logo`))
// logoName.forEach((name) => {
//   const fileExtension = getFileExtension(name)
//   const fileName = name.replace('.' + fileExtension, '')
//   // console.log(`src/assets/logo/${name}`)
//   pages[fileName] = {
//     entry: `src/assets/logo/${name}`,
//     filename: `logo/${fileName}.png`
//   }
// })

const chromeName = getEntryFile(path.resolve(`src/entry`))

const iframeName = getEntryFile(path.resolve(`src/iframe`))

function getFileExtension(filename) {
  return /[.]/.exec(filename) ? /[^.]+$/.exec(filename)[0] : undefined
}
chromeName.forEach((name) => {
  const fileExtension = getFileExtension(name)
  const fileName = name.replace('.' + fileExtension, '')
  pages[fileName] = {
    entry: `src/entry/${name}`,
    template: 'public/index.html',
    filename: `${fileName}.html`
  }
})

iframeName.forEach((name) => {
  const fileExtension = getFileExtension(name)
  const fileName = name.replace('.' + fileExtension, '')
  pages[fileName] = {
    entry: `src/iframe/${name}`,
    template: 'public/index.html',
    filename: `iframe/${fileName}.html`
  }
})


const isDevMode = process.env.NODE_ENV === 'development'

module.exports = {
  pages,
  filenameHashing: false,
  // chainWebpack: (config) => {
  //   config.plugin('copy').use(require('copy-webpack-plugin'), [
  //     {
  //       patterns: [
  //         {
  //           from: path.resolve(`src/manifest.json`),
  //           to: `${path.resolve('dist')}/manifest.json`
  //         }
  //       ]
  //     }
  //   ])
  // },
  configureWebpack: {
    resolve: {
      alias: {
        '@': path.resolve('src')
      }
    },
    output: {
      filename: `js/[name].js`,
      chunkFilename: `[name].js`
    },
    devtool: isDevMode ? 'inline-source-map' : false,
    plugins: [
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      new CopyWebpackPlugin({
        patterns: [
          {
            from: 'src/assets/logo',//想要复制的文件夹
            to: `${path.resolve('dist')}/logo` //复制在哪个文件夹
          },
          {
            from: path.resolve(`src/manifest.json`),
            to: `${path.resolve('dist')}/manifest.json`
          },
          // {
          //   from: path.resolve(`src/rules`),
          //   to: `${path.resolve('dist')}/rules`
          // }
        ]
      })
    ],
  },
}
