const pathToRegexp = require('path-to-regexp')

export const testDocument = (doc) => {
  const { project } = doc
  const screensPattern = project.getOption('patterns.screens', '*screens*')

  return pathToRegexp(screensPattern).test(doc.id)
}

export const decorate = (doc) => {

  Object.assign(doc, {
    buildPageConfig(options = {}) {
      if (doc.fileExtname === '.md') {
        return markdownPageConfig(doc)
      } else if (doc.fileExtname === '.js') {
        return javascriptPageConfig(doc)
      }    
    }
  })

  return doc
}

export const javascriptPageConfig = (doc, options = {}) => {
  const { 
    buildRoute = (v) => v,
    publicRoot = /.*screens\/?/,
  } = options

  return {
    id: doc.id,
    idParts: doc.idParts,
    baseRelativePath: doc.baseRelativePath,
    isIndex: doc.isIndex,
    route: buildRoute(formatId(doc.id)).replace(publicRoot, '/'),
    meta: {
      id: doc.id,
      cacheKey: doc.cacheKey,
      lastModified: doc.get('file.stat.mtime')
    },  
  }
}

export const formatId = (id) => id.replace(/index.*$/,'').replace(/\/$/,'')

export const markdownPageConfig = (doc, options = {}) => {
  const { frontmatter = {} } = doc.exportables

  const {
    publicRoot = /.*screens\/?/,
    buildRoute = (v) => v,
  } = options

  return {
    id: doc.id,
    route: buildRoute(frontmatter.route || formatId(doc.id)).replace(publicRoot, '/'),
    idParts: doc.idParts,
    baseRelativePath: doc.baseRelativePath,
    isIndex: doc.isIndex,
    meta: {
      id: doc.id,
      cacheKey: doc.cacheKey,
      ...frontmatter,
    },
  }
}