<template>
    <ClientOnly>
      <Panel header="Maintainance / Type" class="bg-white rounded-4" style="margin-top: 78px;">
      
        
          <div tag="form" class="g-3 mb-20 needs-validation" novalidate @submit.prevent="checkForm">
            <div class="grid nested-grid">
              <div class="col-4">
                <p>Image Galery</p>
              </div>
              <div class="col-8">
                  <div class="grid">
                    <div class="col-12 gap-2">
                      <label for="bezeichnung">Description *</label>
                      <InputText class="col-12"
                                              v-model="bezeichnung"
                                              invalidFeedback="Please provide a description of the clothing-type"
                                              validFeedback="Looks good!"
                                              required
                                          />
                      <small id="bezeichnung-help">Enter a description for the clothing</small>
                      <InputText type="hidden" v-model="id" />
                    </div>
                  
                    <div class="col-12 gap-3 flex" style="margin-bottom:40px;">
                      
                        <Button severity="primary" label=" NEW " icon="pi pi-check" @click="openNew" />
                        <Button severity="secondary" label=" UPDATE " icon="pi pi-file-edit" @click="onUpdate()" />
                        <Button severity="danger" label=" DELETE " icon="pi pi-trash" @click="onDelete()" />
                        <Button type="reset" severity="warning" label=" RESET " icon="pi pi-undo" />                      
                    </div> 
                  </div>
              </div>
          </div>
          </div>
              <!--<MDBContainer class="bg-white rounded-4"> -->
                <div class="grid" style="margin-bottom:40px;">
                  <div class="col-12">
                     <DataTable class="p-datatable-sm" :filters="filters" dataKey="id" filterDisplay="row" :value="typen" 
                          showGridlines stripedRows paginator :rows="10" :rowsPerPageOptions="[5, 10, 20, 50]" 
                          :globalFilterFields="['bezeichnung']"  
                          v-model:selection="selectedTyp" selection-mode="single" @row-select="onRowSelect" :meta-key-selection="false"
                          tableStyle="min-width: 50rem;">
                          <template #header>
                            <div class="flex justify-content-end">
                                <span class="p-input-icon-left">
                                    <i class="pi pi-search" />
                                    <InputText v-model="filters['global'].value" placeholder="Keyword Search" />
                                </span>
                            </div>
                          </template>
                          <template #empty> No customers found. </template>
                          <!--<template #loading> Loading customers data. Please wait. </template> -->
                        <Column v-for="col of columns" :key="col.field" :field="col.field" :header="col.header" sortable :filter-field="col.field" >
                          
                        </Column>
                          
                    </DataTable>
                  
                  </div>
                </div> 
            <!--</MDBContainer>-->

          
          <template #fallback>
            <!-- this will be rendered on server side -->
            <p>Loading comments...</p>
          </template>
          <Dialog :visible="createTypDialog" :style="{width: '450px'}" header="New Clothing Type" :modal="true" class="p-fluid">
            <div class="field">
                <label for="bezeichnung">Description</label>
                <InputText id="bezeichnung" v-model.trim="typ.bezeichnung" required="true" autofocus />
                <small id="bezeichnung-help" >Enter a description for the clothing</small>
            </div>
            <template #footer>
                <Button label="Cancel" icon="pi pi-times" text @click="hideDialog"/>
                <Button label="Save" icon="pi pi-check" text @click="onSubmit(typ)" />
            </template>
          </Dialog>
      </Panel>
      </ClientOnly>
      
  </template>
  
  

  <script setup lang="ts">
    //import { MDBBtn, MDBCol, MDBCheckbox, MDBInput, MDBRow, MDBContainer } from "mdb-vue-ui-kit";
    import { ref } from "vue";
    import { FilterMatchMode } from "primevue/api";
    import { useToast } from 'primevue/usetoast';

    interface cTyp {
      id: number;
      bezeichnung: string;
    }

    const bezeichnung = ref("");
    //const loading = ref(true); 
    const selectedTyp = ref("");
    const id = ref("");
    const toast = useToast();
    const createTypDialog = ref(false);
    const typ = ref({id: 0, bezeichnung: ''});
    const checkForm = (event: Event) => {
    event.target.classList.add("was-validated");
  };
    const {data: typen } = await useFetch('http://ubodroid-2:8081/api/v1/typ');
  
    const columns = [
      { field: 'id', header: '#'}, 
      { header: 'Description', field: 'bezeichnung'},
    ];

    const filters = ref({
      global: { value: null, matchMode: FilterMatchMode.CONTAINS },
      bezeichnung: {value: null, matchMode: FilterMatchMode.STARTS_WITH }
    })

    const onRowSelect = (event) => {
      id.value = event.data.id;
      bezeichnung.value = event.data.bezeichnung;
      toast.add({ severity: 'info', summary: 'Type Selected', detail: 'Description: ' + event.data.bezeichnung, life: 3000 });
    };

    const openNew = () => {
    typ.value = {};
    createTypDialog.value = true;
    };

    const hideDialog = () => {
    createTypDialog.value = false;
    };
    
    async function onSubmit(t: cTyp) {
      let fd = new FormData();
      fd.append('bezeichnung', t.bezeichnung);
      await $fetch('http://ubodroid-2:8081/api/v1/typ',{
      method: 'POST',
      body: fd
      });
      createTypDialog.value = false;
      toast.add({ severity: 'success', summary: 'New Type created', detail: 'Description: ' + t.bezeichnung, life: 3000 });
      await refreshNuxtData();
    console.log('POST ausgeführt...'+ bezeichnung);
    } 

    async function onUpdate() {
      let fd = new FormData();
      fd.append('bezeichnung', bezeichnung.value);
      fd.append('id', id.value)
      await $fetch('http://ubodroid-2:8081/api/v1/typ/'+id.value,{
      method: 'PUT',
      body: fd
    });
    console.log('UPDATE ausgeführt...'+ bezeichnung);
    } 
    
    async function onDelete() {
      let fd = new FormData();
      fd.append('bezeichnung', bezeichnung.value);
      fd.append('id', id.value)
      await $fetch('http://ubodroid-2:8081/api/v1/typ/'+id.value,{
      method: 'DELETE',
      body: fd
    });
    await refreshNuxtData();
    console.log('DELETE ausgeführt...'+ bezeichnung);
    } 
    
    
  </script>