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

type driver = {
  id:number
  name:string
}

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

    const file = ref<File | null>();
    const form = ref<HTMLFormElement>();
    const drivers:Ref<driver[]> = ref([])
    const selectedDriver:Ref<number> = ref(0);

    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];
      }
    }

    var save = async () => {

      if (!file.value) {
        alert("Bitte wählen Sie eine Datei aus, bevor Sie sie hochladen.");
        return;
      }

      const formData = new FormData();
      formData.append("file", file.value);
      formData.append("driverId", selectedDriver.value.toString());
      
      try {
        const response = await fetch('/track', {
          method: 'POST',
          body: formData,
        });

        if (response.ok) {
          const result = await response.json();
          emit("response", result);
          alert("Datei erfolgreich hochgeladen!");
        } else {
          console.error('Fehler beim Hochladen:', response.statusText);
          alert("Fehler beim Hochladen der Datei.");
        }

      } catch (error) {
        console.error("upload failed:", error);
        alert("failed to upload file.");
      }

    }

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

    return { 
      close, 
      fileInputChange,
      selectedDriver,
      save,
      localizedUploadHeader
    };
  },
});
</script>


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

      <h2 class="card-title">File Upload</h2>

      <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">Click</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="selectedDriver=driver.id">{{ driver.name }}</a></li>
        </ul>
      </div>
      <button class="btn btn-success" v-on:click="save">Upload</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>