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

const Browse = {
  oninit: function(vnode) {
  },

  mArticles: function(vnode, articles) {
    return articles.map(article => {
      return m(m.route.Link, {
        href: ['', article.publish_at.getFullYear(), article.publish_at.getMonth() + 1, article.path_short].join('/'),
        style: article.avif_preview ? `background-image: url('${article.avif_preview}')` : null,
      }, [
        m('span', lang.printdate(article.publish_at)),
        m('span', article.name),
      ])
    })
  },
  
  mMonth: function(vnode, year) {
    return year.branches.map(month => {
      return [
        m('.gallery-month', lang.months[month.title]),
        m('.group', this.mArticles(vnode, month.videos))
      ]
    })
  },

  view: function(vnode) {
    let articles = videos.month?.videos || videos.year?.videos || videos.Articles

    return [
      api.loading ? m('div.loading-spinner') : null,
      videos.error
        ? m('div.full-error', { onclick: videos.refreshTree }, [
            videos.error, m('br'), 'Click here to try again'
          ])
        : null,
      m('.gallery', [
        videos.month
          ? m('.group', this.mArticles(vnode, articles))
          : null,
        videos.year && !videos.month
          ? this.mMonth(vnode, videos.year)
          : null,
        !videos.year
          ? videos.Tree.slice(-1).map(year => {
              return [
                m('.gallery-year', year.title),
                this.mMonth(vnode, year),
              ]
            })
          : null
      ]),
    ]
  },
}

module.exports = Browse
