<script lang="ts">
import type { Content } from '../types/content'
export default {
    props:['jsonContent'],
    data: () => {
        const rawHtml: string = ""
        return{
          rawHtml
        }
    },
    setup(props){
        return{
            props
        }

    },
    methods: {
        reloadContent(el: HTMLElement, jsonContent : Array<Content>){
            if(jsonContent && jsonContent.length > 0){
                for(const contentItem of jsonContent){
                    let itemEl:HTMLElement | null = null
                    switch(contentItem?.type){
                        case "text":
                            let contentText = contentItem?.text
                            if(!contentText){
                                contentText = ""
                            }
                            contentText = contentText.replace(/\n/g, "<br />");
                            if(contentItem.bold){
                                const bold =  document.createElement("b")
                                bold.insertAdjacentHTML("beforeend", contentText)
                                el.append(bold)
                            }else{
                                el.insertAdjacentHTML("beforeend", contentText)
                            }

                            break
                        case "paragraph":
                            itemEl = document.createElement("p")
                            el.append(itemEl)

                            break
                        case "heading":
                            itemEl = document.createElement("h"+contentItem.level)
                            el.append(itemEl)
                            break
                        case "list":
                            itemEl = document.createElement("ul")
                            el.append(itemEl)
                            break
                        case "list-item":
                            itemEl = document.createElement("li")
                            el.append(itemEl)
                            break
                        case "link":
                            itemEl = document.createElement("a")
                            itemEl.setAttribute("href", contentItem.url || "#")
                            el.append(itemEl!)
                            break


                    }
                    if(contentItem.children && contentItem.children.length > 0){
                      this.reloadContent(itemEl!, contentItem.children)
                    }
                }
            }
        },
        updateContent(){
            const div =  document.createElement("div")
            this.reloadContent(div, this.props.jsonContent)
            this.rawHtml = div.innerHTML
        }
    },
    mounted () {
        this.updateContent()
    },
    updated(){
        this.updateContent()
    }
}
</script>

<template >
  <div v-html="rawHtml"></div>
</template>
