const _richText_text_styles_ = ['bold', 'underline', 'italic', 'danger', 'sup', 'sub']

function renderRichText(body) {
    let nodes = []
    if (Array.isArray(body)) {
        body.forEach(part => {
            nodes.push(renderRichText(part))
        })
    } else {
        let sections = Array.isArray(body.sections) ? body.sections : []
        sections.forEach(section => {
            nodes.push(renderSection(section))
        })
    }
    return nodes
}

function renderSection(section) {
    let blocks = Array.isArray(section.blocks) ? section.blocks : []
    let inline = blocks.length > 1
    let node = document.createElement('p')
    blocks.forEach(block => {
        node.appendChild(renderBlock(block, inline))
    })
    return node
}

function renderBlock(block, inline) {
    let container = document.createElement('span')
    let type = ''
    if (block.type === 'text') {
        type = 'text'
        if (block.param != undefined) {
            _richText_text_styles_.forEach(style => {
                if (block.param[style] === true) {
                    type += ' ' + style
                }
            })
        }
        container.textContent = block.value
    } else if (block.type === 'image') {
        type = 'image loading'
        if (inline === true) {
            type += ' inline'
        }
        let img = container.appendChild(new Image())
        img.src = block.value
        img.onload = function () {
            this.parentNode.className = this.parentNode.className.replace(/loading/g, '')
        }
    } else if (block.type === 'audio') {
        type = 'audio'
        let audio = container.appendChild(new Audio())
        audio.src = block.value
        audio.controls = true
        audio.setAttribute("type", "audio/mpeg")
    }
    container.className = type
    return container
}