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

// 指法文件夹位置
const filesDir = path.join(__dirname, './fingering')
// const filesDir = path.join(__dirname, './pages/detail')
// const filesDir = path.join(__dirname, './pages/detail/tips/')

// 需要处理的文件后缀
const suffixs = ['png', 'svg']

const dirs = fs.readdirSync(path.resolve(filesDir))

;(async function() {

  for (const dir of dirs) {
    const exportJson = {}
    const dirFullPath = path.join(filesDir, dir)
    // const dirFullPath = path.join(filesDir, './icons')
    fs.stat(dirFullPath, (err, stat) => {
      if (!err && stat.isDirectory()) {
        const files = fs.readdirSync(dirFullPath).filter(file => suffixs.includes(file.split('.').pop()))
        for (const file of files) {
          const fileNames = file.split('.')
          const fileBuffer =  fs.readFileSync(path.join(dirFullPath, file))
          const fileType = fileNames[1] === 'svg' ? 'svg+xml' : fileNames[1]
          const str = `data:image/${fileType};base64,` + Buffer.from(fileBuffer, 'binary').toString('base64')
          exportJson[fileNames[0]] = str
        }
        fs.writeFileSync(path.join(dirFullPath, 'index.json'), JSON.stringify(exportJson, null, 2))
      }
    })
  }
})()
