const fs = require('fs-extra')
const path = require('path')
const yargs = require('yargs')
const appRootDir = require('app-root-dir')
const fileUtils = require('./file-utils')

const { dir = 'drafts' } = yargs.argv

let strResult = ''
const result = [];

// IIFE
(async function generateData () {
  const DIR_SCOPE = path.resolve(appRootDir.get(), `contents/${dir}/`)
  console.log(`Generating index.js in folder ${dir}...`)

  try {
    const filenames = await fileUtils.readDirSync(DIR_SCOPE)

    filenames.forEach(function (filename) {
      const pathDir = path.join(DIR_SCOPE, filename)
      const isDir = fs.lstatSync(pathDir).isDirectory()
      if (isDir) {
        result.push(filename)
      }
    })

    strResult = `
// THIS IS AN AUTOGENERATED FILE.
// DO NOT EDIT THIS FILE DIRECTLY.
export default {
data: ${JSON.stringify(result.reverse())}
}
  `

    console.log(`Success generate index.js in directory ${dir}`)

    fileUtils.writeFile(path.join(DIR_SCOPE, 'index.js'), strResult)
  } catch (err) {
    console.log(`Error on read folder ${dir}`, err)
  }
})()
