<script lang="ts">
import { defineComponent, SetupContext, ref, Ref } from 'vue';
import GetLocalizedText from "../classes/language";
import Message from "./message.vue";

type driver = {
	id: number
	name: string
}

type vehicle = {
	id: number
	name: string
}


export default defineComponent({
	emits: ['close', 'response'],
	components: { Message },
	name: 'settings',
	props: ["drivers"],
	setup(props, { emit }: SetupContext) {

		const file = ref<File | null>();
		const form = ref<HTMLFormElement>();
		const drivers: Ref<driver[]> = ref([])
		const vehicles: Ref<vehicle[]> = ref([])
		const selectedDriverID: Ref<number> = ref(1);
		const selectedVehicleID: Ref<number> = ref(1);
		const selectedDriverName: Ref<String> = ref("N/A");
		const selectedVehicleName: Ref<String> = ref("N/A");

		// button text
		const buttonText: Ref<string> = ref('Upload');

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

		props.drivers.forEach((d: driver) => {
			drivers.value.push({ id: d.id, name: d.name })
		});

		// localized text
		// if there is time left this gets moved out to its own class
		var localizedUploadHeader: Ref<string> = ref("")
		async function getLocalization() {
			localizedUploadHeader.value = await GetLocalizedText("localizedUploadHeader")
		}

		var fileInputChange = async ($event: Event) => {
			const target = $event.target as HTMLInputElement;
			if (target && target.files) {
				file.value = target.files[0];
				console.log(`selected file: ${file.value}`);
			}
		}

		// handles sending webrequests to the backend
		const getDrivers = 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/driver", {
				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++) {
					drivers.value.push({ id: jsonBody[i]["id"], name: jsonBody[i]["name"] })
				}
			} else {
				
				alert(`upload failed: ${await response.text()}`)
				console.log(await response.text())
				messageType.value = "error";
				message.value = `upload failed: ${await response.statusText}`;
			}
		}

		// 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
			})

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

				// convert vehicles from json response to processable data
				for (let i = 0; i < jsonBody.length; i++) {
					vehicles.value.push({ id: jsonBody[i]["id"], name: jsonBody[i]["name"] })
				}
			} else {

				alert(`upload failed: ${await response.text()}`)
				console.log(await response.text())
				messageType.value = "error";
				message.value = `upload failed: ${await response.text()}`;
				buttonText.value = "Upload";
			}
		}

		var save = async () => {

			if (!file.value) {

				alert("please select a file");
				messageType.value = "warning";
				message.value = "please select a file";
				return;
			}

			const formData = new FormData();
			formData.append("file", file.value);
			formData.append("driverID", selectedDriverID.value.toString());
			formData.append("vehicleID", selectedVehicleID.value.toString());

			buttonText.value = 'Loading <span class="loading loading-spinner loading-xs"></span>';

			try {

				console.log('Request Body:', formData);

				const response = await fetch('http://localhost:5000/upload', {
					method: 'POST',
					body: formData,
				});

				if (response.ok) {
					const result = await response.json();
					emit("response", result);
					
					messageType.value = "success";
					message.value = `Upload Successful`;
					buttonText.value = 'Upload Successful';

					setTimeout(() => {
						buttonText.value = "Upload";
					}, 2000);
				} else {

					alert(`upload failed: ${await response.statusText}`)
					console.error('upload failed: ', await response.statusText);
					messageType.value = "error";
					message.value = `upload failed: ${await response.statusText}`;
					buttonText.value = "Upload";
				}
			} catch (error) {

				alert(`upload failed: ${error}`)
				messageType.value = "error";
				message.value = `upload failed: ${error}`;
				buttonText.value = "Upload";
			}

		}

		getVehicles()
		getDrivers()
		getLocalization()
		const close = () => {
			emit("close");
		};

		return {
			close,
			fileInputChange,
			selectedDriverID,
			selectedVehicleID,
			selectedDriverName,
			selectedVehicleName,
			save,
			drivers,
			vehicles,
			localizedUploadHeader,
			buttonText,
			messageType,
			message
		};
	},
});
</script>


<template>
	<div class="card bg-base-100 w-full shadow-xl" style="">
		<div class="card-body">

			<h2 class="card-title">File Upload</h2>
			<Message v-if="messageType!='None'" :type="messageType" :message="message" @close="message=''; messageType='None'" style="z-index: 1000;"></Message>
			<button class="btn btn-error close round" @click="close()">
				<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px"
					fill="#e8eaed">
					<path
						d="m256-200-56-56 224-224-224-224 56-56 224 224 224-224 56 56-224 224 224 224-56 56-224-224-224 224Z" />
				</svg>
			</button>
			<label class="form-control w-full max-w-xs">
				<div class="label">
					<span class="label-text">Upload a GPX File</span>
				</div>
				<input type="file" ref="file" v-on:change="fileInputChange($event)"
					class="file-input file-input-bordered w-full max-w-xs" />
			</label>
			<div class="dropdown dropdown-bottom">
				select Driver: <div tabindex="0" role="button" class="btn m-1"> {{ selectedDriverName }}</div>
				<ul tabindex="0" class="dropdown-content menu bg-base-100 rounded-box z-[1] w-52 p-2 shadow">
					<li v-for="driver in drivers"><a
							v-on:click="selectedDriverID = driver.id; selectedDriverName = driver.name">{{ driver.name
							}}</a></li>
				</ul>
			</div>
			<div class="dropdown dropdown-bottom">
				select Vehicle: <div tabindex="0" role="button" class="btn m-1"> {{ selectedVehicleName }}</div>
				<ul tabindex="0" class="dropdown-content menu bg-base-100 rounded-box z-[1] w-52 p-2 shadow">
					<li v-for="vehicle in vehicles"><a
							v-on:click="selectedVehicleID = vehicle.id; selectedVehicleName = vehicle.name">{{
								vehicle.name }}</a></li>
				</ul>
			</div>
			<button class="btn btn-success" v-on:click="save" v-html="buttonText"></button>
		</div>
	</div>
</template>

<style scoped>
.settingsBody {
	position: absolute;
	margin: 10% 10% 0 10%;
	width: 80%;
	z-index: 10;
}

.btn.close {
	position: absolute;
	right: 30px;
	top: 30px;
	margin: 0;
}
</style>