const Authentication = require('./authentication')

window.adminRoutes = {}

let loadingAdmin = false
let loadedAdmin = false
let loaded = 0
let elements = []

const onLoaded = function() {
  loaded++
  if (loaded < 2) return

  Authentication.setAdmin(Authentication.currentUser && Authentication.currentUser.rank >= 10)
  loadedAdmin = true
  m.route.set(m.route.get())
}

const onError = function(a, b, c) {
  Authentication.clearToken()
  elements.forEach(function(x) { x.remove() })
  loadedAdmin = loadingAdmin = false
  loaded = 0
  m.route.set('/')
}

const loadAdmin = function(user) {
  if (loadingAdmin) {
    if (loadedAdmin) {
      Authentication.setAdmin(user && user.rank >= 10)
    }
    return
  }
  if (!user || user.rank < 10) return

  loadingAdmin = true

  let token = Authentication.getToken()
  let element = document.createElement('link')
  elements.push(element)
  element.setAttribute('rel', 'stylesheet')
  element.setAttribute('type', 'text/css')
  element.setAttribute('href', '/assets/admin.css?token=' + token)
  element.onload = onLoaded
  element.onerror = onError
  document.getElementsByTagName('head')[0].appendChild(element)

  element = document.createElement('script')
  elements.push(element)
  element.setAttribute('type', 'text/javascript')
  element.setAttribute('src', '/assets/admin.js?token=' + token)
  element.onload = onLoaded
  element.onerror = onError
  document.body.appendChild(element)
  
  element = document.createElement('script')
  elements.push(element)
  element.setAttribute('type', 'text/javascript')
  element.setAttribute('src', '/assets/editor.js')
  element.onload = onLoaded
  element.onerror = onError
  document.body.appendChild(element)
}

Authentication.addEvent(loadAdmin)
if (Authentication.currentUser) {
  loadAdmin(Authentication.currentUser)
}

const Loader = {
  view: function() {
    return m('div.wrapper', m('div.loading-spinner'))
  },
}
const AdminResolver = {
  onmatch: function(args, requestedPath) {
    if (window.adminRoutes[args.path]) {
      return window.adminRoutes[args.path][args.id && 1 || 0]
    }
    return Loader
  },
  render: function(vnode) { return vnode },
}

module.exports = AdminResolver
