import { ref, watch, onUnmounted } from 'vue'
import { useApi } from '@/includes/composables'

export const useInfinityScroll = (query) => {

    let observer = null

    const domElement = ref(null)
    const lastID = ref(0)
    const cursor = ref('')
    const data = ref({})

    const { loading, result, error, callAPI } = useApi(query)


    watch(domElement, (changeElement) => {
        // console.log(changeElement)
        createObserver(changeElement)
    })

    watch(result, (response) => {
        if(!response) return
        console.log(response.records)
        Object.entries(response.records).forEach(([key,value]) => {
            lastID.value = value[value.length - 1]?.id
            if(data.value[[key]]){
                data.value[[key]] = { ...value, ...data.value[[key]] }
            }else{
                data.value[[key]] = value
            }
        })

        cursor.value = response.cursor
        Object.entries(response.records).forEach(([,value]) => {
            lastID.value = value[value.length - 1]?.id
        })
    })

    const createObserver = (dom) => {
        observer?.disconnect()
        if(!cursor.value) return
        if (dom) {
            const intersectionCallback = (entries) => {
                entries.forEach((entry) => {
                    if (entry.isIntersecting) {
                        removeObserver(entry.target)
                        callAPI()
                    }
                })
            }
            observer = new IntersectionObserver(intersectionCallback, {})
            observer.observe(dom)
        }
    }

    const removeObserver = (target) => {
        observer.unobserve(target)
        observer?.disconnect()
    }

    const refetchApi = () => {
        cursor.value = ''
        data.value = {}
        observer?.disconnect()
        callAPI()
    }

    const domNodeFn = (el, idx) => {
        if(lastID.value === idx){
            if(el){
                domElement.value = el.$el
            }
        }
    }

    onUnmounted(() => {
        observer?.disconnect()
    })

    // watchEffect(onInvalidate => {
    //     onInvalidate(() => observer?.disconnect())

    //     console.log(1)
    // })

    return {
        domElement,
        loading,
        error,
        callAPI,
        cursor,
        data,
        lastID,
        refetchApi,
        domNodeFn
    }
}
