const m = require('mithril')
const Authentication = require('./authentication')
const PageTree = require('./page_tree')

const DarkModeStorageName = 'nfp_sites_darkmode'

const Menu = {
  oninit: function(vnode) {
    this.currentActive = 'home'
    this.error = ''
    this.loading = false
    this.onbeforeupdate()

    if (!PageTree.Tree.length) {
      this.refreshTree()
    }

    
  },

  onbeforeupdate: function() {
    this.darkIsOn = localStorage.getItem(DarkModeStorageName)

    let currentPath = m.route.get()

    if (currentPath === '/') this.currentActive = 'home'
    else if (currentPath === '/login') this.currentActive = 'login'
    else if (currentPath && currentPath.startsWith('/page')) this.currentActive = currentPath.slice(currentPath.lastIndexOf('/') + 1)
  },

  refreshTree: function(vnode) {
    this.loading = true
    this.error = ''

    PageTree.refreshTree()
    .catch((err) => {
      this.error = 'Error while getting menu tree: ' + err.message + '. Click here to try again.'
    })
    .then(() => {
      this.loading = false
      m.redraw()
    })
  },

  logOut: function() {
    Authentication.clearToken()
    m.route.set('/')
  },

  toggleDarkMode: function() {
    this.darkIsOn = !this.darkIsOn
    if (this.darkIsOn) {
      localStorage.setItem(DarkModeStorageName, true)
    } else {
      localStorage.removeItem(DarkModeStorageName)
    }
    document.body.className = (this.darkIsOn ? 'nightmode ' : 'daymode ')
      + (window.supportsavif ? 'avifsupport' : 'jpegonly')
  },

  view: function() {
    return [
      m('header', [
        m('div.inside', [
          m(m.route.Link,
            { href: '/', class: 'title' },
            [
              m('div.logo.spritesheet'),
              m('h1', 'NFP Moe'),
            ]
          ),
          m('aside', [
            Authentication.currentUser
              ? [
                  m('p', [
                    'Welcome ' + Authentication.currentUser.name + '. ',
                    m('button', { onclick: this.logOut }, '(Log out)'),
                  ]),
                  m('div', [
                    m(m.route.Link, { href: '/admin/articles/add' }, 'Create article'),
                    m(m.route.Link, { href: '/admin/articles' }, 'Articles'),
                    m(m.route.Link, { href: '/admin/pages' }, 'Pages'),
                    // m(m.route.Link, { hidden: Authentication.currentUser.rank < 100, href: '/admin/staff' }, 'Staff'),
                  ])
                ]
              : null,
            m('button',
              { onclick: this.toggleDarkMode.bind(this) },
              this.darkIsOn ? 'Day mode' : 'Night mode'
            ),
          ])
        ]),
      ]),
      m('nav', [
        m('div.inside', [
          m(m.route.Link, {
            href: '/',
            class: this.currentActive === 'home' ? 'active' : '',
          }, 'Home'),
          this.loading ? m('div.loading-spinner') : null,
          PageTree.Tree.map((page) => {
            let className = ''
            if (this.currentActive === page.path) {
              className += 'active '
            }
            return m(m.route.Link, {
              href: '/page/' + page.path,
              class: className,
            }, page.name)
          }),
        ])
      ]),
      this.error ? m('div.error', { onclick: this.refreshTree.bind(this) }, this.error) : null,
    ]
  },
}

module.exports = Menu
