import { useAuth } from '@websanova/vue-auth/src/v3.js';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { ProjectService } from '../service/ProjectService';
import { LoadingStore } from './LoadingStore';

export const UserPrefStore = defineStore('userpref_store', () => {

    const user = ref(null)
    const userLoaded = ref(false)
    const selectedApp = ref(null)
    const loadingStore = LoadingStore()


    async function fetchUserData(){
      
      const auth = useAuth();
      loadingStore.user_loading = true;
      await auth.fetch().then((fetchedUser) => {
          user.value = fetchedUser.data.data;
          selectedApp.value = user.value.selectedApplication;
          userLoaded.value = true;
          loadingStore.user_loading = false;
      }).catch((error) => {
          reject(error);
      });
    };

    async function updateSelectedProject(project) {
      try {
          loadingStore.user_loading = true;
          selectedApp.value = null;
          // Aspetta che l'aggiornamento del progetto finisca
          await ProjectService.updateSelectedProject(project);
          
      } catch (error) {
          console.error("Errore durante l'aggiornamento del progetto:", error);
      } finally {
          // Assicurati che il caricamento venga disabilitato anche in caso di errore
          loadingStore.user_loading = false;
      }
  };
  

  

    async function setSelectedApp(app){
      loadingStore.user_loading = true;
      await ProjectService.updateSelectedApplication(app);
      selectedApp.value = app;
      loadingStore.user_loading = false;      
    }

    const selectedProject = computed(() => user.value.selectedProject)
    //const availableApp = computed(() => user.value.selectedProject.lstApplications)
    const availableApp = computed(() => {
      if (user.value.selectedProject!=null) {
          return user.value.selectedProject.lstApplications
      } else {
          return []
      }
  });

  const getSelApp = computed(() => {
    return selectedApp.value
  })
  

  
    return { user,fetchUserData,userLoaded,selectedProject,availableApp,getSelApp,setSelectedApp,selectedApp, updateSelectedProject }
  })