<template>
    <ClientOnly>
        <Card style="margin-top: 78px; min-height: 200px;"> 
            <template #content>
                <Panel header="Managing photos" class="rounded-4 bg-white" >
                    <template #icons>
                        <Button class="mr-2" @click="onNew" label=" NEW " icon="pi pi-plus" />
                    </template>
                    <div class="grid">
                        <FileUpload :custom-upload="true"
                            @uploader="onAdvancedUpload"
                            :multiple="true"
                            accept="image/*"
                            :maxFileSize="10000000" 
                            class="col-6"
                            style="max-width: 50%;">
                            <template #content>
                            <ul v-if="uploadedFiles && uploadedFiles[0]">
                                <li v-for="file of uploadedFiles[0]" :key="file">
                                    {{ file.name }} - {{ file.size }} bytes
                                </li>
                            </ul>
                            </template>
                            <template #empty>
                                <p>Drag and drop files to here to upload.</p>
                            </template>
                        </FileUpload>
                        <DataView class="col-6" id="dv" :value="photos" paginator :rows="5">
                        <template #list="slotProps">
                            <div class="col-12">
                                <div class="flex flex-column xl:flex-row xl:align-items-start p-4 gap-4">
                                    <img class="w-2 shadow-2 block xl:block mx-auto border-round" :src="`${pfad}/thumb-${slotProps.data.pfad}`" :alt="slotProps.data.pfad" />
                                    <div class="flex flex-column sm:flex-row justify-content-between align-items-center xl:align-items-start flex-1 gap-4">
                                        <div class="flex flex-column align-items-center sm:align-items-start gap-3">
                                            <div class="text-2xl font-bold text-900">{{ slotProps.data.kurzbeschreibung }}</div>
                                            <div class="flex align-items-center gap-3">
                                                <span class="flex align-items-center gap-2">
                                                    <i class="pi pi-tag"></i>
                                                    <span class="font-semibold">Linked with bought clothes no. {{ slotProps.data.itembid }}</span>
                                                    <span class="font-semibold">Linked with evaluated clothes no. {{ slotProps.data.itemextid }}</span>
                                                </span>
                                                
                                            </div>
                                            <div class="col-12 gap-3 flex">
                                                    <Button severity="info" @click="linkToB(slotProps.data.id)" target="_blank" label=" Bought " icon="pi pi-link" />
                                                    <Button severity="success" @click="linkToE(slotProps.data.id)" label=" Evaluated " icon="pi pi-link" />                                                    
                                            </div>
                                        </div>
                                        
                                    </div>
                                </div>
                            </div>
                        </template>
                    </DataView>
                    </div>
                    
                </Panel>
            </template>
        </Card>
    </ClientOnly>
    



</template>

<script setup lang="ts">
import { ref, defineProps } from "vue";
import { useDialog } from 'primevue/usedialog';
const pfad = '/photos';

const config = useRuntimeConfig();

interface cPho {
    id: number;
    pfad: string;
    itembid: number;
    itemextid: number;
}

//const photo = ref({id:0,pfad:'',itembid:0,itemextid:0});
import { useToast } from 'primevue/usetoast';
import LinkItemB  from "./LinkItemB.vue";
import LinkItemExt  from "./LinkItemExt.vue";
const toast = useToast();  
const dialog = useDialog(); 
const uploadedFiles = ref([]);
const {data: photos } = await useFetch(config.public.apiHostname + 'api/v1/pho');

const onAdvancedUpload = async (event) => {
    const files = event.files;
    console.log('files = ',files);
    let file: any;
    let fd = new FormData();
    let i = 0;
    for (i; i< files.length; i++) {
        console.log('file = ', files[i]);
        fd.append('file', files[i]);
        console.log('files = ', i, file); 
    }
    
    const imgUpload = await $fetch(config.public.apiHostname + "api/v1/upload", {
        method: "POST",
        body: fd,
      });
      if (imgUpload) {
        console.log(imgUpload);
        toast.add({
          severity: "info",
          summary: "Success",
          detail: "File Uploaded",
          life: 10000,
        });
      }
}



async function linkToB (id: number) {
    const photo = await useFetch(config.public.apiHostname + 'api/v1/pho/'+id);
    let pho: cPho;
    console.log(photo.data.value);
    pho = photo.data.value;
    console.log(pho);
    let refid = ref();
    dialog.open(LinkItemB, { onClose(options) {
        refid = options?.data;
        console.log('RefId = ', refid);
        if (refid) {
            doUpdate(refid, pho, false);
        }
    
    },});
    
}

async function linkToE(id: number) {
    const photo = await useFetch(config.public.apiHostname + 'api/v1/pho/'+id);
    let pho: cPho;
    console.log(photo.data.value);
    pho = photo.data.value;
    console.log(pho);
    let refid = ref();
    dialog.open(LinkItemExt, { onClose(options) {
        refid = options?.data;
        console.log('RefId = ', refid);
        if (refid) {
            doUpdate(refid, pho, true);
        }
    
    },});
}

async function doUpdate(ref: any, pho: cPho, updext: boolean){
    let fd = new FormData();
    fd.append('id', pho.id.toString());
    fd.append('pfad', pho.pfad);
    if (updext) {
        fd.append('itembid', pho.itembid.toString());
        fd.append('itemextid', ref.id.toString());
    }
    fd.append('itembid', ref.id.toString());
    fd.append('itemextid', pho.itemextid.toString());
      const updPho = await $fetch(config.public.apiHostname + "api/v1/pho/"+pho.id, {
        method: "PUT",
        body: fd,
      });
    if (updPho) {
        toast.add({
          severity: "info",
          summary: "Success",
          detail: "Photo updated",
          life: 10000,
        });
        refreshNuxtData();

    }

}

</script>