import { tools } from '../../store/Modules/tools'
import { useQuasar } from 'quasar'
import { useI18n } from 'vue-i18n'
import { useUserStore } from '@store/UserStore'
import { useGlobalStore } from '@store/globalStore'
import { CDownloadJsonFile } from '@src/components/CDownloadJsonFile'
import { PropType, defineComponent, onMounted, ref } from 'vue'
import type { IMyPage } from '@src/model'

export default defineComponent({
  name: 'CExportImportPage',
  props: {
    idPage: {
      type: String,
      required: true,
    },
    esporta: {
      type: Boolean,
      required: true,
    },
    nomefileprop: {
      type: String,
      required: true,
    },
  },
  components: { CDownloadJsonFile },
  setup(props) {
    const $q = useQuasar()
    const { t } = useI18n()
    const globalStore = useGlobalStore()

    const myrec = ref(<IMyPage | undefined>{})

    const nomefile = ref(<string>'')
    const testoJson = ref(<any>'')
    const fileContent = ref('')

    const ris = ref('')

    const onFileChange = (event: any) => {
      const file = event.target.files[0];
      if (file && file.type === "application/json") {
        const reader = new FileReader();
        reader.onload = (e: any) => {
          fileContent.value = e.target.result; // Carica il contenuto del file JSON
        };
        reader.readAsText(file);
      } else {
        tools.showNotif($q, 'Seleziona un file JSON valido.', { color: 'negative', icon: 'notifications' })
      }
    }

    const importaPagina = async () => {
      try {
        if (!fileContent.value) {
          tools.showNotif($q, 'Nessun file JSON caricato.', { color: 'negative', icon: 'notifications' })
          return
        }

        // Chiama la funzione di importazione passandole il contenuto del file
        ris.value = await globalStore.importPage(fileContent.value, $q, t);

      } catch (error) {
        console.error(error);
      }
    };

    async function esportaPagina() {

      if (myrec.value) {
        testoJson.value = await globalStore.exportPage(myrec.value.path, $q, t)
      }
    }

    async function mounted() {
      nomefile.value = props.nomefileprop

      myrec.value = globalStore.getPageById(props.idPage)

    }

    onMounted(mounted)

    return {
      myrec,
      tools,
      testoJson,
      esportaPagina,
      importaPagina,
      nomefile,
      onFileChange,
      ris,
      fileContent,
    }
  },
})
