import { useEffect, useState } from 'preact/hooks'

import { createContext } from 'preact'

export const MetadataContext = createContext({})

export const useCurrentUser = onLoaded => {
    const [user, setUser] = useState(null)

    const logout = () => {
        setUser(null)
    }

    useEffect(async () => {
        const res = await fetch(`/api/current-user`, {
            credentials: 'include',
        })
        const user = await res.json()
        setUser(user)

        console.log(`Current user is`, user)

        onLoaded?.(user)
    }, [])

    useEffect(() => {
        console.log(user)
    }, [user])

    return [user, logout]
}

export const useReadResource = (url, initialValue) => {
    const [value, setValue] = useState(initialValue)

    function refresh() {
        const controller = new AbortController()

        fetch(url, { signal: controller.signal })
            .then(res => {
                if (res.ok) {
                    return res.json()
                } else {
                    return initialValue
                }
            })
            .then(newValue => {
                setValue(newValue)
            })

        return controller
    }

    useEffect(() => {
        const controller = refresh()
        return () => {
            controller.abort()
        }
    }, [])

    return [value, refresh]
}
