const m = require('mithril')
const Article = require('./article')
const api = require('./api')
const media = require('./media')
const NotFoundView = require('./site_404')

window.LoadComments = false
window.HyvorLoaded = false
window.HYVOR_TALK_WEBSITE = 7544

const SiteArticle = {
  oninit: function(vnode) {
    this.error = ''
    this.loading = false
    this.showLoading = null
    this.data = {
      article: null,
      files: [],
    }
    this.showcomments = false

    if (window.__nfpdata) {
      this.path = m.route.param('id')
      this.data = window.__nfpdata
      window.__nfpdata = null
      this.afterData()
    } else {
      this.fetchArticle(vnode)
    }
  },

  onbeforeupdate: function(vnode) {
    if (this.path !== m.route.param('id')) {
      this.fetchArticle(vnode)
    }
  },

  fetchArticle: function(vnode) {
    this.error = ''
    this.path = m.route.param('id')
    this.showcomments = false

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

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

    api.sendRequest({
      method: 'GET',
      url: '/api/articles/' + this.path,
    })
    .then((result) => {
      this.data = result
      this.afterData()
    }, (err) => {
      this.error = err.message
    })
    .then(() => {
      clearTimeout(this.showLoading)
      this.showLoading = null
      this.loading = false
      m.redraw()
    })
  },

  afterData: function() {
    if (!this.data.article) {
      this.error = 'Article not found'
    }
  },

  view: function(vnode) {
    let article = this.data.article

    return [
      this.loading
        ? m('.inside.vertical', [
            m('div.actions', m('div.lb-link')),
            m('article.fullsize', [
              m('h2.title', m('div.lb-main.lb--long')),
              m('div.row', [
                m('div.cover', m('picture.lb.nobg')),
                m('div.description', [
                  m('div.lb-main.lb--long'),
                  m('div.lb-main'),
                  m('div.lb-main.lb--medium'),
                  m('div.lb-main.lb--medium'),
                  m('div.lb-main'),
                  m('p', m.trust(' ')),
                  m('fileinfo', [
                    m('div.lb-main.lb--slim.lb--longest'),
                    m('ul', [
                      m('li', m('div.lb-main.lb--slim.lb--longest')),
                      m('li', m('div.lb-main.lb--slim.lb--longest')),
                    ])
                  ]),
                ]),
              ]),
            ]),
          ])
        : null,
      !this.loading && this.error === 'Article not found'
        ? NotFoundView.view()
        : null,
      !this.loading && this.error && this.error !== 'Article not found'
        ? m('div.wrapper', m('div.error', {
            onclick: () => {
              this.error = ''
              this.fetchPage(vnode)
            },
          }, 'Article error: ' + this.error + '. Click here to try again'))
        : null,
      (!this.loading && article
        ? m('.inside.vertical', [
            m('div.actions', [
              '« ',
              m(m.route.Link, {
                href: article.page_path
                  ? '/page/' + article.page_path
                  : '/'
                }, article.page_name || 'Home'),
              Authentication.currentUser
                ? [
                    m('div.filler'),
                    'Actions:',
                    m(m.route.Link, { href: '/admin/articles/' + article.id }, 'Edit article'),
                  ]
                : null,
            ]),
            article ? m(Article, { full: true, files: this.data.files, article: article }) : null,
            window.LoadComments
              ? m('div#hyvor-talk-view', { oncreate: function() {
                  window.HYVOR_TALK_CONFIG = {
                    url: false,
                    id: article.path,
                    loadMode: scroll,
                  }
                  if (!window.HyvorLoaded) {
                    window.HyvorLoaded = true
                    var s = document.createElement('script')
                    s.src = 'https://talk.hyvor.com/web-api/embed.js';
                    s.type = 'text/javascript'
                    // s.setAttribute('crossorigin', '')
                    // s.setAttribute('data-timestamp', +new Date());
                    document.body.appendChild(s);
                  } else {
                    hyvor_talk.reload()
                  }
                }}, m('div.loading-spinner'))
            : m('button.comments', {
              style: 'display: none',
                onclick: function() { window.LoadComments = true },
              }, 'Open comment discussion'),
          ])
        : null),
    ]
  },
}

module.exports = SiteArticle