<script lang="ts">
import { defineComponent, Ref, ref, SetupContext } from 'vue';

type vehicle = {
  id: number
  name: string
  licenseplate: string
}

export default defineComponent({
  name: 'map',
  setup(_, { emit }: SetupContext) {

    const vehicleName: Ref<string> = ref("")
    const licensePlate: Ref<string> = ref("")
    const vehicleList: Ref<vehicle[]> = ref([])

    // values for UI Information distribution
    const messageType: Ref<string> = ref("");
    const message: Ref<string> = ref("");

    // handles getting all existing drivers
    const getVehicles = async () => {
      const headers: Headers = new Headers()
      headers.set('Content-Type', 'application/json')
      headers.set('Accept', 'application/json')

      const request: RequestInfo = new Request("http://localhost:5000/vehicle", {
        method: "GET",
        headers: headers
      })

      var response = await fetch(request)
      // make sure the request was successfull
      if (response.ok) {
        var jsonBody = await response.json()

        // convert vehicles from json response to processable data
        for (let i = 0; i < jsonBody.length; i++) {
          let plate = "N/A"
          let vehicle = jsonBody[i]
          if (vehicle["licensePlate"] != undefined) {
            plate = vehicle["licensePlate"];
          }

          vehicleList.value.push({ id: vehicle["id"], name: vehicle["name"], licenseplate: plate })
        }
      } else {
        console.log(await response.text())
        messageType.value = "error";
				message.value = `loading vehicles failed with error: ${await response.text()}`;
      }
    }

    // handles sending webrequests to the backend
    const createVehicle = async () => {
      const headers: Headers = new Headers()

      headers.set('Content-Type', 'application/json')
      headers.set('Accept', 'application/json')

      const requestBody = JSON.stringify({ name: vehicleName.value, licensePlate: licensePlate.value });

      const request: RequestInfo = new Request("http://localhost:5000/vehicle", {
        method: "POST",
        headers: headers,
        body: requestBody
      })

      var response = await fetch(request)
      // make sure the request was successfull
      if (response.ok) {
        var jsonBody = await response.json()
        vehicleList.value.push({ id: jsonBody["body"], name: vehicleName.value, licenseplate: "N/A" })
      } else {
        console.log(await response.text())
        messageType.value = "error";
				message.value = `creating vehicle failed with error: ${error}`;
      }
    }

    getVehicles()
    return {
      createVehicle,
      vehicleName,
      licensePlate,
      vehicleList,
      message,
      messageType
    };
  },
});
</script>


<template>
  <Message v-if="type == 'none'" :type="messageType" :message="message" @close="message = ''; messageType = 'None'"></Message>
  <div class="overflow-x-auto">
    <table class="table">
      <!-- head -->
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td></td>
          <td><input type="text" placeholder="Vehicle Name" class="input input-bordered w-full "
              v-model="vehicleName" /></td>
          <td><input type="text" placeholder="License Plate" class="input input-bordered w-full "
              v-model="licensePlate" /></td>
          <td><a class="btn btn-success w-full" v-on:click="createVehicle">Create Vehicle</a></td>
        </tr>
        <tr v-if="vehicleList.length == 0">
          <th>
            <div class="skeleton h-4 w-full"></div>
          </th>
          <td>
            <div class="skeleton h-4 w-full"></div>
          </td>
          <td>
            <div class="skeleton h-4 w-full"></div>
          </td>
          <td><a class="btn btn-error w-full" v-on:click="createVehicle">Delete Vehicle</a></td>
          <td></td>
        </tr>
        <tr v-for="vehicle in vehicleList">
          <th>{{ vehicle.id }}</th>
          <td>{{ vehicle.name }}</td>
          <td>{{ vehicle.licenseplate }}</td>
          <td><a class="btn btn-error w-full" v-on:click="createVehicle">Delete Vehicle</a></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped></style>