<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';

const xml = ref('');
const transform = ref('');
const transformPlaceholder = ref('');
const engine = ref('');
const result = ref('');

const activeXmlTool = ref('');

async function submit() {
  const engineEndpoint = engine.value == "libxml" ? "libxml" : "java";
  const url = document.location.protocol + "//" + document.location.hostname + "/" + engineEndpoint + "/" + activeXmlTool.value;

  var version = "1.0";
  if (engine.value == "saxon")
    version = "3.0"

  var requestBody = JSON.stringify({
    "data": xml.value,
    "process": transform.value,
    "processor": engine.value,
    "version": version
  });

  var request = new Request(url, {
    body: requestBody,
    method: "POST"
  });


  var responseBody = await fetch(request)
    .then(response => response.json())
    .then((body) => body);

  result.value = responseBody.result;
}

watch(activeXmlTool, (tool) => {
  if (tool == "xpath")
    transformPlaceholder.value = "XPath";
  if (tool == "xsd")
    transformPlaceholder.value = "XSD";
  if (tool == "xslt")
    transformPlaceholder.value = "XSLT";
  if (tool == "xquery")
    transformPlaceholder.value = "XQuery";
  
    transform.value = "";
})

onMounted(() => {
  activeXmlTool.value = "xpath";
});
</script>

<template>
  <label for="xpath">XPath</label>
  <input v-model="activeXmlTool" type="radio" id="xpath" name="xmltool" value="xpath" />

  <label for="xslt">XSLT</label>
  <input v-model="activeXmlTool" type="radio" id="xslt" name="xmltool" value="xslt" />

  <label for="xsd">XSD</label>
  <input v-model="activeXmlTool" type="radio" id="xsd" name="xmltool" value="xsd" />
  
  <label for="xquery">XQuery</label>
  <input v-model="activeXmlTool" type="radio" id="xquery" name="xmltool" value="xquery" />
  <br /><br />
  <select name="engine" v-model="engine">
    <option value="saxon" selected>Saxon</option>
    <option value="xalan">Xalan</option>
    <option value="libxml">libXML</option>
  </select>
  <br />
  <textarea v-model="xml" id="xml" placeholder="XML"></textarea>
  <textarea v-model="transform" id="transform" :placeholder="transformPlaceholder"></textarea><br />
  <button @click="submit">Submit</button><br />
  <pre><code>{{ result }}</code></pre>
</template>

<style scoped></style>
