const Dialogue = require('./dialogue')
const api = require('../api')
const Paginator = require('../paginator')

const ItemsPerPage = 20

const AdminArticles = {
  oninit: function(vnode) {
    this.error = ''
    this.loading = false
    this.showLoading = null
    this.data = {
      articles: [],
      total_articles: 0,
    }
    this.currentPage = Number(m.route.param('page')) || 1

    this.fetchArticles(vnode)
  },

  onbeforeupdate: function(vnode) {
    this.currentPage = Number(m.route.param('page')) || 1

    if (this.currentPage !== this.lastpage) {
      this.fetchArticles(vnode)
    }
  },

  fetchArticles: function(vnode) {
    this.error = ''
    this.lastpage = this.currentPage

    document.title = 'Articles Page ' + this.lastpage + ' - Admin NFP Moe'

    if (this.showLoading) {
      clearTimeout(this.showLoading)
    }

    if (this.data.articles.length) {
      this.showLoading = setTimeout(() => {
        this.showLoading = null
        this.loading = true
        m.redraw()
      }, 150)
    } else {
      this.loading = true
    }

    return api.sendRequest({
      method: 'GET',
      url: '/api/auth/articles?page=' + (this.lastpage || 1),
    })
    .then((result) => {
      this.data = result

      this.data.articles.forEach((article) => {
        article.hidden = new Date() < new Date(article.publish_at)
        article.page_path = article.page_path ? '/page/' + article.page_path : '/'
        article.page_name = article.page_name || 'Frontpage'
      })
    }, (err) => {
      this.error = err.message
    })
    .then(() => {
      clearTimeout(this.showLoading)
      this.showLoading = null
      this.loading = false
      m.redraw()
    })
  },

  confirmRemoveArticle: function(vnode, article) {
    this.loading = true
    m.redraw()

    return api.sendRequest({
      method: 'DELETE',
      url: '/api/auth/articles/' + article.id,
    })
    .then(
      () => this.fetchArticles(vnode),
      (err) => { this.error = err.message }
    )
    .then(() => {
      this.loading = false
      m.redraw()
    })
  },
  
  askConfirmRemovePage: function(vnode, article) {
    Dialogue.showDialogue(
      'Delete ' + article.name,
      'Are you sure you want to remove "' + article.name + '" (' + article.path + ')',
      'Remove',
      'alert',
      'Don\'t remove',
      '',
      article,
      this.confirmRemoveArticle.bind(this, vnode))
  },

  drawArticle: function(vnode, article) {
    return [
      m('tr', {
        class: article.hidden
          ? rowhidden
          : article.is_featured
            ? 'rowfeatured'
            : ''
      }, [
        m('td.nopadding', article.banner_alt_prefix
          ? m('a', { href: article.banner_path, target: '_blank' }, m('img', { src: article.banner_alt_prefix + '_small.avif' }))
          : m.trust('&nbsp;') ),
        m('td.nopadding', article.media_alt_prefix
          ? m('a', { href: article.media_path, target: '_blank' }, m('img', { src: article.media_alt_prefix + '_small.avif' }))
          : m.trust('&nbsp;') ),
        m('td', m(m.route.Link, { href: '/admin/articles/' + article.id }, article.name)),
        m('td', m(m.route.Link, { href: '/article/' + article.path }, 'View')),
        m('td', m(m.route.Link, { href: article.page_path }, article.page_name)),
        m('td.right', article.publish_at.replace('T', ' ').split('.')[0]),
        m('td.right', article.admin_name),
        m('td.right', m('button', { onclick: this.askConfirmRemovePage.bind(this, vnode, article) }, 'Remove')),
      ]),
    ]
  },

  view: function(vnode) {
    return [
      m('div.admin', [
        m('div.inside.vertical', [
          m('div.actions', [
            m('div.filler'),
            m('span', 'Actions:'),
            m(m.route.Link, { href: '/admin/articles/add' }, 'Create new article'),
          ]),
          m('h2.title', 'All articles'),
          m('div.container', [
            m('div.error', {
              hidden: !this.error,
              onclick: function() { vnode.state.error = '' },
            }, this.error),
            this.loading
              ? m('div.loading-spinner.full')
              : m('table', [
                  m('thead', 
                    m('tr', [
                      m('th', 'Banner'),
                      m('th', 'Cover'),
                      m('th', 'Title'),
                      m('th', 'Path'),
                      m('th', 'Page'),
                      m('th.right', 'Publish'),
                      m('th.right', 'By'),
                      m('th.right', 'Actions'),
                    ])
                  ),
                  m('tbody', this.data.articles.map((article) => this.drawArticle(vnode, article))),
                ],
            ),
            m(Paginator, {
              base: '/admin/articles',
              page: this.currentPage,
              perPage: ItemsPerPage,
              total: this.data.total_articles,
            }),
          ]),
        ]),
      ]),
    ]
  },
}

module.exports = AdminArticles
