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

export const JobLogs = ({}) => {
    const [logLines, setLogLines] = useState([])

    useEffect(async () => {
        const res = await fetch(location.href + '/logs?format=raw')
        const rawLogs = (await res.text()).trim()

        if (rawLogs.length > 0) setLogLines(rawLogs.split('\n'))

        // Setup SSE
        const es = new EventSource(location.href + '/logs?format=sse')
        es.addEventListener('message', ({ data }) => {
            const event = JSON.parse(data)
            setLogLines(lines => [
                ...lines,
                event.content,
            ])
        })
    }, [])

    return (
        <pre><code>{logLines.join('\n')}</code></pre>
    )
}
