/*
Blocks:
  * Paragraph
  * Header
  * SimpleImage
  * Quote
  * CodeTool
  * List
  * Delimiter
  * RawTool

Other:
 * InlineCode
*/

const EditorBlock = {
  oninit: function(vnode) {
    this.id = null
    this.output = null
    this.onbeforeupdate(vnode)
  },

  onbeforeupdate: function(vnode) {
    if (!vnode.attrs.block && !this.id) {
      return false
    }
    if (vnode.attrs.block && vnode.attrs.block.id
        && vnode.attrs.block.id === this.id) {
      return false
    }

    if (vnode.attrs.block && vnode.attrs.block.id
        && vnode.attrs.block.id !== this.id) {
      this.renderblock(vnode)
    } else {
      this.output = null
    }
  },

  renderblock: function(vnode) {
    let block = vnode.attrs.block
    this.id = block.id
    switch (block.type) {
      case 'header':
        this.output = m('h' + block.data.level, block.data.text)
        break;
      case 'paragraph':
        this.output = m('p', m.trust(block.data.text))
        break
      case 'htmlraw':
        this.output = m.trust(block.data.html)
        break
      case 'quote':
        this.output = m('blockquote', [
          m('p', block.data.text),
          m('span.author', block.data.caption),
        ])
        break
      case 'list':
        this.output = m(
          block.data.style === 'unordered' ? 'ul' : 'ol',
          block.data.items.map(item => m('li', item))
        )
        break
      case 'code':
        this.output = m('pre', block.data.code)
        break
      default:
        this.output = m('p', m.trust(block))
        break
    }
  },

  view: function(vnode) {
    return this.output
  }
}

module.exports = EditorBlock
