
const slugify = require('slugify')

module.exports = function init({
  prettyPrint = false,
  markdown = { render: str => str },
} = {}) {
  return (loaded, metalsmith, done) => {
    const { collections = {} } = metalsmith.metadata()
    const collectionFiles = Object
      .keys(collections)
      .map((name) => {
        const collection = collections[name]
        const { description = '', ...metadata } = collection.metadata || {}
        const files = collection.map(({
          title,
          contents,
          description = '',
          path,
        }) => ({
          title,
          contents: Buffer.isBuffer(contents)
            ? contents.toString('utf8')
            : contents,
          description: description.length > 0
            ? markdown.render(description)
            : undefined,
          path,
          slug: slugify(title.toLowerCase()),
        }))
        const contentsObj = {
          ...metadata,
          key: name,
          description: description.length > 0
            ? markdown.render(description)
            : undefined,
          files,
        }
        const contents = prettyPrint
          ? JSON.stringify(contentsObj, null, 2)
          : JSON.stringify(contents)
        return { [`${name}.json`]: { contents }}
      })
      .reduce((last, curr) => ({ ...last, ...curr }))

    Object.assign(loaded, collectionFiles)
    done()
  }
}

@@ -1,8 +1,37 @@
+%0Aconst path = require('path')
 %0Aconst s
@@ -1245,32 +1245,33 @@
 ngify(contents)%0A
+%0A
         return %7B
@@ -1270,16 +1270,26 @@
 return %7B
+%0A         
  %5B%60$%7Bnam
@@ -1304,19 +1304,191 @@
 %5D: %7B
- contents %7D
+%0A            contents,%0A          %7D,%0A          %5B%60$%7Bpath.join(name, 'index.html')%7D%60%5D: %7B%0A            contents: '',%0A            description,%0A            ...metadata,%0A          %7D,%0A        
 %7D%0A  

add collection landing pages