const PageTree = require('../page_tree')
const Dialogue = require('./dialogue')
const api = require('../api')

const AdminPages = {
  oninit: function(vnode) {
    this.error = ''
    this.pages = []

    document.title = 'Pages - Admin NFP Moe'
    this.fetchPages(vnode)
  },

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

    return api.sendRequest({
      method: 'GET',
      url: '/api/auth/pages',
    })
    .then((result) => {
      this.pages = result.tree
    }, (err) => {
      this.error = err.message
    })
    .then(() => {
      this.loading = false
      m.redraw()
    })
  },

  confirmRemovePage: function(vnode, page) {
    this.loading = true
    m.redraw()

    return api.sendRequest({
      method: 'DELETE',
      url: '/api/auth/pages/' + page.id,
    })
    .then(
      () => Promise.all([
        PageTree.refreshTree(),
        this.fetchPages(),
      ]),
      (err) => { this.error = err.message }
    )
    .then(() => {
      this.loading = false
      m.redraw()
    })
  },

  askConfirmRemovePage: function(vnode, page) {
    Dialogue.showDialogue(
      'Delete ' + page.name,
      'Are you sure you want to remove "' + page.name + '" (' + page.path + ')',
      'Remove',
      'alert',
      'Don\'t remove',
      '',
      page,
      this.confirmRemovePage.bind(this, vnode))
  },

  drawPage: function(vnode, page) {
    return [
      m('tr', [
        m('td.nopadding', page.banner_alt_prefix
          ? m('a', { href: page.banner_path, target: '_blank' }, m('img', { src: page.banner_alt_prefix + '_small.avif' }))
          : m.trust('&nbsp;') ),
        m('td.nopadding', page.media_alt_prefix
          ? m('a', { href: page.media_path, target: '_blank' }, m('img', { src: page.media_alt_prefix + '_small.avif' }))
          : m.trust('&nbsp;') ),
        m('td', [
          page.parent_id ? m('span.subpage', ' - ') : null,
          m(m.route.Link, { href: '/admin/pages/' + page.id }, page.name),
        ]),
        m('td', m(m.route.Link, { href: '/page/' + page.path }, '/page/' + page.path)),
        m('td.right', page.updated_at.replace('T', ' ').split('.')[0]),
        m('td.right', m('button', { onclick: this.askConfirmRemovePage.bind(this, vnode, page) }, 'Remove')),
      ]),
    ].concat(page.children ? page.children.map(AdminPages.drawPage.bind(this, vnode)) : [])
  },

  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/pages/add' }, 'Create new page'),
          ]),
          m('h2.title', 'All pages'),
          m('div.container', [
            m('div.error', {
              hidden: !this.error,
              onclick: function() { vnode.state.error = '' },
            }, this.error),
            this.loading
              ? m('div.loading-spinner')
              : m('table', [
                  m('thead', 
                    m('tr', [
                      m('th', 'Banner'),
                      m('th', 'Cover'),
                      m('th', 'Title'),
                      m('th', 'Path'),
                      m('th.right', 'Updated'),
                      m('th.right', 'Actions'),
                    ])
                  ),
                  m('tbody', this.pages.map(AdminPages.drawPage.bind(this, vnode))),
                ],
            ),
          ]),
        ]),
      ]),
    ]
  },
}

module.exports = AdminPages
