import { render } from 'preact'
import { useEffect, useState } from 'preact/hooks'
import { MessageWidget } from './components/MessageWidget.jsx'
import { PieChartWidget } from './components/PieChartWidget.jsx'
import { useUser } from './util.js'

const WidgetTypes = {
    pie: PieChartWidget,
    message: MessageWidget,
}

const Widget = ({ type, value }) => {
    const CustomWidget = WidgetTypes[type]

    return (
        <div class={'widget ' + type}>
            <CustomWidget {...value} />
        </div>
    )
}

const App = () => {
    const user = useUser()

    const [widgets, setWidgets] = useState([])

    useEffect(() => {
        fetch('/api/dashboard-state')
            .then(res => res.json())
            .then(state => setWidgets(state.widgets))
            .catch(e => console.error(e))
    }, [])

    return (
        <>
            <header>
                <div class="logo">Dashboard</div>
                <div class="spacer">&bull;</div>
                <div class="machine">space.phc.dm.unipi.it</div>
            </header>
            <p>
                (Viewing page as <b>{user}</b>)
            </p>
            <div class="widgets">
                {widgets.map(w => (
                    <Widget {...w} />
                ))}
            </div>
        </>
    )
}

render(<App />, document.querySelector('main'))
