<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 deleting a vehicle
		const deleteVehicle = async (vehicleID: number) => {
			const headers: Headers = new Headers()
			headers.set('Content-Type', 'application/json')
			headers.set('Accept', 'application/json')

			const requestBody = JSON.stringify({ id: vehicleID });

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

			var response = await fetch(request)
			if (!response.ok) {
				
				alert(`deleting vehicle failed with error: ${await response.text()}`)
				messageType.value = "error";
				message.value = `deleting vehicle failed with error: ${await response.text()}`;
			} else {

				alert("delete vehicle")
				messageType.value = "success";
				message.value = `deleted vehicle`;
			}
		}

		// 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 {
				
				alert(`loading vehicles failed with error: ${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 {
				
				alert(`creating vehicle failed with error: ${error}`)
				messageType.value = "error";
				message.value = `creating vehicle failed with error: ${error}`;
			}
		}

		getVehicles()
		return {
			createVehicle,
			vehicleName,
			licensePlate,
			vehicleList,
			message,
			messageType,
			deleteVehicle
		};
	},
});
</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"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-plus-lg" viewBox="0 0 16 16">
  <path fill-rule="evenodd" d="M8 2a.5.5 0 0 1 .5.5v5h5a.5.5 0 0 1 0 1h-5v5a.5.5 0 0 1-1 0v-5h-5a.5.5 0 0 1 0-1h5v-5A.5.5 0 0 1 8 2"/>
</svg> 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"> <svg
								xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
								class="bi bi-trash3-fill" viewBox="0 0 16 16">
								<path
									d="M11 1.5v1h3.5a.5.5 0 0 1 0 1h-.538l-.853 10.66A2 2 0 0 1 11.115 16h-6.23a2 2 0 0 1-1.994-1.84L2.038 3.5H1.5a.5.5 0 0 1 0-1H5v-1A1.5 1.5 0 0 1 6.5 0h3A1.5 1.5 0 0 1 11 1.5m-5 0v1h4v-1a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5M4.5 5.029l.5 8.5a.5.5 0 1 0 .998-.06l-.5-8.5a.5.5 0 1 0-.998.06m6.53-.528a.5.5 0 0 0-.528.47l-.5 8.5a.5.5 0 0 0 .998.058l.5-8.5a.5.5 0 0 0-.47-.528M8 4.5a.5.5 0 0 0-.5.5v8.5a.5.5 0 0 0 1 0V5a.5.5 0 0 0-.5-.5" />
							</svg> 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 v-if="vehicle.id != 1" class="btn btn-error w-full"
							v-on:click="deleteVehicle(vehicle.id)">Delete Vehicle</a></td>
				</tr>
			</tbody>
		</table>
	</div>
</template>

<style scoped></style>