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

import { createContext } from 'preact'
import { server } from './api.jsx'

export const MetadataContext = createContext({})

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

    const logout = async () => {
        await server.post('/api/logout')
        setUser(null)
    }

    useEffect(async () => {
        const user = await server.get('/api/current-user')
        setUser(user)
        onLoaded?.(user)
    }, [])

    return [user, logout]
}

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

    function refresh() {
        const controller = new AbortController()
        const realUrl = typeof url === 'function' ? url() : url
        fetch(realUrl, { 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]
}
