<script setup lang="ts">

const props = defineProps({
    xml: {type: String, required: true},
    isMinimizer: {type: Boolean}
})

const emit = defineEmits(["update:result"])

function process() {
    var request:Request = prepareRequest();
    fetchRequest(request).then((data) => {
        sendProcessedData(data);
    })
}

function prepareRequest():Request {
    var request = new Request(prepareURL(), {
        body: prepareRequestBody(),
        method: "POST"
    });
    return request;
}

function prepareURL(): string {
    var mode = "formatting";
    if (props.isMinimizer)
        mode = "minimize";
    return document.location.protocol + "//" + document.location.hostname + "/java/json/" + mode;
}

function prepareRequestBody():string {
    var requestBody = props.xml;
    return requestBody;
}

async function fetchRequest(request: Request):Promise<JSON> {
    var responseBody = await fetch(request)
    .then(response => response.json())
    .then((body) => body);
    console.log(responseBody);
    return responseBody;
}

function sendProcessedData(data: JSON) {
    emit("update:result", data);
}
</script>

<template>
    <button class="tool-button" @click="process()">{{ props.isMinimizer ? "Minimize" : "Format" }}</button>
</template>

<style scoped></style>
