const m = require('mithril')
const videos = require('./videos')
const Authentication = require('./authentication')
const lang = require('./lang')

const Menu = {
  oninit: function(vnode) {
    this.currentActive = 'home'
    this.loading = false
    if (!videos.Tree.length) {
      videos.refreshTree()
    }
    this.onbeforeupdate()
  },

  onbeforeupdate: function() {
    videos.calculateActiveBranches()
    let currentPath = m.route.get()
  },

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

  view: function() {
    let tree = videos.Tree
    let last = videos.Tree[videos.Tree.length - 1]
    let hasId = m.route.param('id')

    return [
      m('nav', [
        m('h4', m(m.route.Link, { href: '/' }, lang.header_title /* Filadelfia archival center */)),
        m('a.link.changelang', { onclick: lang.langtoggle }, lang.lang_current),
        Authentication.currentUser?.rank >= 100
          ? m(m.route.Link, { class: 'upload', href: '/upload' }, lang.upload_goto) // Upload
          : null,
        Authentication.currentUser
          ? m(m.route.Link, { class: 'link', href: '/logout' }, lang.logout)
          : m(m.route.Link, { class: 'upload', href: '/login' }, lang.login_submit) // Upload,
        // m('button.logout', { onclick: this.logOut }, lang.header_logout), // Log out
      ]),
      videos.error
        ? m('div.error', { onclick: videos.refreshTree }, [
            videos.error, m('br'), 'Click here to try again'
          ])
        : null,
      !videos.error
        ? [
            m('.nav', m('.inner', tree.map(year => {
              return m(m.route.Link, {
                class: [videos.year === year ? 'active' : '',
                        !year.videos.length ? 'empty' : ''].join(' '),
                href: ['', (videos.year !== year && year !== last) || hasId ? year.title : '' ].filter(x => x).join('/') || '/',
              }, year.title)
            }))),
            videos.year
              ? m('.nav', m('.inner', videos.year.branches.map(month => {
                  return m(m.route.Link, {
                    class: [videos.month === month ? 'active' : '',
                            !month.videos.length ? 'empty' : ''].join(' '),
                    href: ['', videos.year.title, videos.month !== month || hasId ? month.title : null ].filter(x => x).join('/'),
                  }, lang.months[month.title])
                })))
              : null,
          ]
        : null,
    ]
  },
}

module.exports = Menu
