const Fileinfo = require('./fileinfo')
const EditorBlock = require('./editorblock')
const media = require('./media')

const Article = {
  oninit: function(vnode) {
    this.lastId = null
    this.onbeforeupdate(vnode)
  },

  onbeforeupdate: function(vnode) {
    let article = vnode.attrs.article

    if (this.lastId !== article.id) {
      this.lastId = article.id

      let pictureCover = '(max-width: 639px) calc(100vw - 10px), '
        + '(max-width: 1000px) calc(100vw - 265px), '
        + '400px'
      if (vnode.attrs.full) {
        pictureCover = '(max-width: 1280) calc(100vw - 2rem), '
          + '1248px'
      }
      
      this.pictureData = media.generatePictureSource(
        article,
        pictureCover)
    }
  },

  view: function(vnode) {
    let article = vnode.attrs.article
    let files = vnode.attrs.files || article.files || []

    return m('article', {
      class: vnode.attrs.full ? 'fullsize' : '',
    }, [
      m(m.route.Link,
        { href: '/article/' + article.path, class: 'title' },
        m('h2.title', article.name)
      ),
      m('div.row', [
        media.getArticlePicture(
          this.pictureData,
          !vnode.attrs.full,
          vnode.attrs.full ? article.media_path : '/article/' + article.path,
          'Image for news item ' + article.name,
        ),
        m('div', [
          m('div.description.content',
            article.content.blocks.map(block => {
              return m(EditorBlock, { block: block })
            }),
          ),
          files.map(function(file) {
            return m(Fileinfo, { file: file, trim: true })
          }),
          m('p.meta', [
            'Posted ',
            (article.page_path ? ['in ', m(m.route.Link, { href: '/page/' + article.page_path }, article.page_name), ' '] : ''),
            'at ' + (article.publish_at.replace('T', ' ').split('.')[0]).substr(0, 16),
            ' by ' + (article.admin_name || 'Admin'),
          ]),
        ]),
      ]),
    ])
  },
}

module.exports = Article