const api = require('./api')

const Tree = window.__nfptree && window.__nfptree.tree || []
const TreeMap = new Map()

exports.Tree = Tree
exports.TreeMap = TreeMap

function parseLeaf(tree) {
  for (let branch of tree) {
    TreeMap.set(branch.path, branch)

    if (branch.children && branch.children.length) {
      parseLeaf(branch.children)
    }
  }
}

parseLeaf(Tree)

function processPageBranch(arr, branches, prefix) {
  branches.forEach((page) => {
    arr.push({ id: page.id, name: prefix + page.name })
    if (page.children && page.children.length) {
      processPageBranch(arr, page.children, page.name + ' -> ')
    }
  })
}

exports.getFlatTree = function() {
  let arr = []
  processPageBranch(arr, Tree, '')
  return arr
}

exports.refreshTree = function() {
  return api.sendRequest({
    method: 'GET',
    url: '/api/pagetree',
  })
  .then(pages => {
    Tree.splice(0, Tree.length)
    Tree.push.apply(Tree, pages.tree)
    TreeMap.clear()
    parseLeaf(Tree)
  })
}