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

export const testDocument = (doc) => {
  const { project } = doc
  const pagesPattern = project.getOption('patterns.pages', '(screens|pages)*/:name/(index|screen).:extension')

  return pathToRegexp(pagesPattern).test(doc.path)
}

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 = /.*(pages\screens)\/?/i,
  } = 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|page|screen).*$/i,'').replace(/\/$/,'').split('/').slice(-2)

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

  const {
    publicRoot = /.*(pages|screens)\/?/i,
    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,
    },
  }
}