/**
 * React Static Boilerplate
 * https://github.com/koistya/react-static-boilerplate
 * Copyright (c) Konstantin Tarkus (@koistya) | MIT license
 */

import glob from "glob"
import { join } from "path"
import sortBy from "lodash.sortby"

module.exports = function tagLoader(source) {
  this.cacheable()
  const target = this.target
  const callback = this.async()

  if (target === "node") {
    source = source.replace("import 'babel/polyfill';", "") // eslint-disable-line no-param-reassign
  }

  glob("**/*.{js,jsx,markdown}", { cwd: join(__dirname, "../../pages/blog") }, (err, files) => {
    if (err) {
      return callback(err)
    }

    const tagList = {}
    files.forEach(file => {
      const tags = require(`../../pages/blog/${file}`).metadata.tags // eslint-disable-line global-require
      tags.forEach(tag => (tagList[tag] = tag))
    })

    const tags = sortBy(Object.keys(tagList))

    if (tags.length) {
      return callback(null,
                      source.replace(" tags = []",
                                     (` tags = ${JSON.stringify(tags)}`)))
    }

    return callback(new Error("Cannot find any blog pages."))
  })
}

@@ -233,16 +233,332 @@
 ortby%22%0A%0A
+function capitalize(string) %7B%0A  return string.split(%22 %22)%0A    .map(word =%3E word.replace(/(?:%5E%7C%5Cs)%5CS/g, a =%3E a.toUpperCase()))%0A    .join(%22 %22)%0A%7D%0A%0Aconst PRESERVED = %7B%0A  nye: %22NYE%22,%0A  usa: %22USA%22,%0A%7D%0A%0Afunction formattedTag(tag) %7B%0A  const lowerTag = tag.toLowerCase()%0A  return PRESERVED%5BlowerTag%5D %7C%7C capitalize(lowerTag)%0A%7D%0A%0A
 module.e
@@ -1148,19 +1148,33 @@
 tagList%5B
+formattedTag(
 tag
+)
 %5D = tag)

Format tags... actually, this probably belongs in transpiling