<template>
  <div class="grid">
    <div class="col-12">
      <Card>
        <template #title>
          <div
            class="flex flex-column md:flex-row gap-2 md:justify-content-between md:align-items-center"
          >
            <div class="align-item-start">
              <h4>Galleries</h4>
            </div>
          </div>
        </template>
        <template #content>
          <div class="block">
            <Galleries
              :key="galleryKey"
              :initialize="initialize"
              v-model="formData"
              @update:modelValue="loadPreview"
            ></Galleries>
          </div>
          <div class="flex justify-content-end mt-3">
            <Button
            :loading="saving"
              severity="info"
              :disabled="!enableSave"
              @click="uploadGallery"
              class="float-right"
              raised
              label="Save"
            ></Button>
          </div>
        </template>
      </Card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from "vue";
import { GalleryService } from "@/service/website/GalleryService";
import PrimeTable from "@/components/PrimeTable.vue";
import ConfirmDelete from "@/components/ConfirmDelete.vue";
import { useToast } from "primevue/usetoast";
import { useRoute, useRouter } from "vue-router";
import Galleries from "./components/Galleries.vue";

const saving = ref(false)
const imgSrc = ref("")
const galleryKey = ref(0);
const initialize = ref([]);
const initForm = ref([]);
const initData = ref([...initForm.value]);
const formData = ref([...initForm.value]);
const state = reactive({
  modal: {
    show: false,
  },
});
const enableSave = computed(
  () => JSON.stringify(formData.value) !== JSON.stringify(initData.value) && formData.value || 1
);
const mKey = ref(0);
const route = useRoute();
const router = useRouter();
const toast = useToast();
const galleryService = new GalleryService();

const getData = () => {
  galleryService.getData().then((res) => {
    let galleries = res.data.galleries;
    imgSrc.value = galleries[0].filepath;
    let images = [];
    for(const gallery of galleries){
      images.push(dataURLtoFile(gallery.filepath,gallery.filename))
    }
    formData.value = images;
    initialize.value = formData.value;
    initData.value = JSON.parse(JSON.stringify(images));
  });
};

function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[arr.length - 1]), 
        n = bstr.length, 
        u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}
const loadPreview = (files) => {
  
};
onMounted(async () => {
  await getData();
});
const formModel = (formValue) => {
  const data = new FormData();
  for (const file of formValue) {
    data.append("images[]", file);
  }
  return data;
};
const uploadGallery = async () => {
  let data = formModel(formData.value);
  await handleUpload(data);
};

const handleUpload = (data) => {
  saving.value = true
  galleryService.save(data).then((res) => {
    let response = res.data;
    saving.value = false
    toast.add({
      severity: "success",
      summary: "Success",
      detail: response.message,
      life: 3000,
    });
  });
};
</script>