text: const { Router } = require('../index')
  const path = require('path')
  let router = new Router()
  const matter = require('gray-matter')
  const glob = require('glob')
  
  function getIndex(dir) {
      return getFile(dir, 'index')
  }
  
  function getFile(dir, file) {
      file = file.replace(/^\//, '')
      let files = glob.sync(`${file}.+(md|html)`, {cwd: dir})
      if (files.length >= 1) {
          return path.join(dir, files[0])
      }
      return ''
  }
  
  function resolveContentFile(ctx) {
      let ctxPath = ctx.path
      let contentRoot = path.join(ctx.app.dir, 'content')
  
      if (ctxPath === '/') {
          return getIndex(contentRoot)
      }
  
      let file = getFile(contentRoot, ctxPath)
      if (file !== '') {
          return file
      }
  
      contentRoot = path.join(contentRoot, ctxPath)
      return getIndex(contentRoot)
  }
  
  router.get('main', '/(.*)',
      async (ctx, next) => {
  
          let contentFile = resolveContentFile(ctx)
          if (contentFile === '') {
              ctx.status = 404
              return next()
          }
  
          const marked = ctx.app.get('marked')
  
          const file = matter.read(contentFile)
          let template = file.data.template || 'default.html'
  
          let ext = path.extname(contentFile)
          let htmlContent
  
          if (ext === '.md') {    
              htmlContent = marked(file.content)
          }
  
          let baseURL = ctx.app.options.base_url ?  ctx.app.config.get('base_url')
              : `${ctx.protocol}://${ctx.host}`
          let data = {
              ...ctx.app.baseViewData(),
              base_url: baseURL,
              page: {
                  title: file.data.title,
              }
          }
          if (ext === '.html') {
              htmlContent = ctx.app.renderString(file.content, data)
          }
  
          data.page.content = htmlContent
          ctx.body =  ctx.app.render(template, data)
          return next()
      })
  
  module.exports = router
  