const path = require('path')
const fileUtils = require('./file-utils');

(async function getDataMarkdown () {
  const DIR_SCOPE = fileUtils.getDirPublished()
  const res = await fileUtils.getAllMarkdown(DIR_SCOPE)
  console.log(`Generating content list based on directory ${DIR_SCOPE}...`)

  const arrayContents = []
  let arraySorted = []

  for (const key in res) {
    const item = res[key]
    arraySorted.push({
      slug: item.slug,
      date: new Date(item.date)
    })
  }

  // sort based on date published
  arraySorted = arraySorted.sort((a, b) => (a.date.getTime() < b.date.getTime()) ? 1 : -1)

  arraySorted.forEach(element => {
    arrayContents.push(element.slug)
  })

  const indexFile = path.resolve(fileUtils.getDirContent(), 'index.js')
  const indexNodeFile = path.resolve(fileUtils.getDirContent(), 'node-index.js')

  fileUtils.writeFile(
    indexFile,
    `// THIS IS AN AUTOGENERATED FILE.
  // DO NOT EDIT THIS FILE DIRECTLY.
  export default { data: ${JSON.stringify(arrayContents)} };
  `
  )
  fileUtils.writeFile(
    indexNodeFile,
    `// THIS IS AN AUTOGENERATED FILE.
  // DO NOT EDIT THIS FILE DIRECTLY.
  module.exports = ${JSON.stringify(arrayContents)};
  `
  )

  console.log('Suceess generate content list')
})()
