import {defineStore} from 'pinia'
import OneSignal from "onesignal-cordova-plugin";
import {Capacitor} from "@capacitor/core";
// @ts-ignore
export const useProfileStore = defineStore('profile', () => {

    const supabase = useSupabaseClient()
    const dataStore = useDataStore()
    const user = useSupabaseUser()
    const toast = useToast()
    const router = useRouter()

    const loaded = ref(false)
    const showProfileSelection = ref(false)
    const ownTenant = ref({
        calendarConfig: {
            eventTypes: []
        },
        timeConfig: {
            timeTypes: []
        },
        tags: {
            documents: [] ,
                products: []
        },
        measures: []
    })


    const profiles = ref([])
    const ownProfiles = ref([])
    const activeProfile = ref([])
    const tenants = ref([])
    const currentTenant = ref(null)


    async function initializeData (userId) {

        let profileconnections = (await supabase.from("profileconnections").select()).data
        let profiles = (await supabase.from("profiles").select("*, role(*)")).data
        let activeProfileConnection = profileconnections.find(i => i.active)
        if(activeProfileConnection) {
            toast.add({title: 'Aktives Profil ausgewählt'})
            console.log("Active Profile selected")
            activeProfile.value = profiles.find(i => i.id === activeProfileConnection.profile_id)
            currentTenant.value = activeProfile.value.tenant

            if(Capacitor.getPlatform() === "ios") {
                OneSignal.initialize("1295d5ff-28f8-46a6-9c62-fe5d090016d7");
                OneSignal.Location.setShared(false)
                OneSignal.Notifications.requestPermission();
                OneSignal.login(activeProfileConnection.user_id)
            }


            await fetchData()
            await dataStore.fetchData()
        } else {
            toast.add({title: 'Kein aktives Profil', color: 'orange'})
            await fetchOwnProfiles()
            await fetchTenants()
            showProfileSelection.value = true
        }


    }

    async function changeProfile(newActiveProfileId) {
        loaded.value = false

        let profileconnections = (await supabase.from("profileconnections").select()).data

        let oldActiveProfileConnection = profileconnections.find(i => i.active)

        const {error} = await supabase.from("profileconnections").update({active: true}).eq("profile_id", newActiveProfileId)

        if(error) {
            console.log(error)
        } else {
            if(oldActiveProfileConnection){
                const {error} = await supabase.from("profileconnections").update({active: false}).eq("profile_id", oldActiveProfileConnection.profile_id)
            }

            reloadNuxtApp({
                path:"/",
                ttl: 10000
            })
        }
    }

    async function fetchData () {
        await fetchOwnProfiles()
        await fetchProfiles()

        await fetchTenants()
        await fetchOwnTenant()

        loaded.value = true
        console.log("Finished Loading")
    }

    function clearStore () {
        loaded.value = false
        ownTenant.value =  {}
        profiles.value = []
        ownProfiles.value = []
        tenants.value = []
    }

    async function fetchOwnTenant () {
        ownTenant.value = (await supabase.from("tenants").select().eq('id', currentTenant.value).single()).data
    }

    async function fetchProfiles () {
        profiles.value = (await supabase.from("profiles").select().eq("tenant",currentTenant.value).order("lastName")).data
    }

    async function fetchOwnProfiles () {
        let profiles = (await supabase.from("profiles").select().order("tenant")).data
        let conns = (await supabase.from("profileconnections").select()).data.map(i => i.profile_id)
        ownProfiles.value = profiles.filter(i => conns.includes(i.id))
    }

    async function fetchTenants () {
        tenants.value = (await supabase.from("tenants").select().order("id",{ascending: true})).data
    }

    const getOwnProfile = computed(()  => {
        return profiles.value.find(i => i.id === user.value.id)

    })

    const getProfileById = computed(() => (itemId) => {
        return profiles.value.find(item => item.id === itemId)
    })

    return {
        //General
        currentTenant,
        loaded,
        showProfileSelection,
        ownTenant,
        initializeData,
        changeProfile,

        //Data
        profiles,
        ownProfiles,
        activeProfile,
        tenants,
        fetchData,
        clearStore,
        fetchOwnTenant,
        getOwnProfile,
        getProfileById
    }


})