<script setup lang="ts">
const props = defineProps(
    {
        formatType: {
            type:String,
            required:true
        },
        code: {
            type:String,
            required:true
        },
        isError: {
            type:Boolean,
            required:false
        },
    }
)

const emit = defineEmits([
    'update:result',
    'update:error'
])

const fetchLink = document.location.protocol + "//" + document.location.hostname + "/libxml/html/" + chooseType(props.formatType);

function chooseType(formatType: String){
    if (formatType == "HTML -> XML"){
        return "convert";
    }
    return formatType.toLowerCase();
}

function getTypeInfo(){
    if( props.code.startsWith("<!DOCTYPE") ){
        return "html"
    }else{
        return "xml"
    }
}

function createBody(){
    return JSON.stringify({
        "data": props.code,
        "processorData": getTypeInfo(),
        "processor": "libxml",
        "version": "1.0"
    });
}


function process(){
    fetch(fetchLink, {body:createBody(), method: "POST"})
        .then( response => response.json() )
        .then( formattedCode => processResponse(formattedCode) )
}

function processResponse(formattedCode : any){
    emit('update:result', formattedCode )
    emit("update:error", formattedCode.status == "ERR")
}

</script>

<template>
<button class="tool-button" @click="process()">{{ formatType }}</button>
</template>