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

type vehicle = {
  id:number
  name:string
}

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

    const vehicleName:Ref<string> = ref("")
    const vehicleList:Ref<vehicle[]> = ref([{id:1,name:"Bike"}])

    // 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("/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
        var vehicles:vehicle[] = []
        for(let i = 0; i < jsonBody.length; i++) {
          vehicles.push(jsonBody["vehicles"][i])
        }

        // push all vehicles into the table
        vehicles.forEach(vehicle => {
          vehicleList.value.push({id: vehicle.id, name: vehicle.name})
        });
      } else {
        alert(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 request: RequestInfo = new Request("/vehicle", {
        method:"POST", 
        headers:headers
      })

      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})
      } else {
        alert(response.text)
      }
    }

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


<template>
  <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 max-w-xs" v-model="vehicleName"/></td>
          <td><a class="btn btn-success" v-on:click="createVehicle">Create Vehicle</a></td>
        </tr>
        <tr v-for="vehicle in vehicleList">
          <th>{{ vehicle.id }}</th>
          <td>{{ vehicle.name }}</td>
          <td><a class="btn btn-warning">Open Editor</a></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
</style>