import { strings } from 'skypager-util'
import set from 'lodash/set'
import get from 'lodash/get'
const {camelCase, snakeCase} = strings

export const treeConfig = (project, options = {}) => (
  project.chain
    .get('documentsMap')
    .mapValues((doc,id) => ({
      doc,
      id,
      idParts: doc.idParts.map(p => camelCase(snakeCase(p).replace(/-/g,'_'))),
      bucket: doc.idParts.map(p => camelCase(snakeCase(p).replace(/-/g,'_'))).slice(0, doc.idParts.length - 1),
    }))
)

export const createDocumentTree = (project, options = {}) => (
  treeConfig(project,options).values()
    .sortBy(cfg => cfg.idParts.length)
    .reduce((memo, cfg) => {
      const existingBucket = get(memo, cfg.bucket, {})
      set(memo, cfg.bucket, existingBucket)
      set(memo, cfg.idParts, options.ready ? cfg.doc.ready : cfg.doc)
      return memo
    }, {})
    .value()
)

export default createDocumentTree
