import _ from 'lodash'
import { render } from 'preact'
import { useEffect, useState } from 'preact/hooks'

import { EventsView } from './components/EventsView.jsx'
import { Toolbar } from './components/Toolbar.jsx'

const App = ({}) => {
    const [eventi, setEventi] = useState([])
    useEffect(() => {
        // Directly copy-pasted from chrome Dev Tools
        // const request = fetch(
        //     'https://apache.prod.up.cineca.it/api/Impegni/getImpegniCalendarioPubblico',
        //     {
        //         headers: {
        //             'content-type': 'application/json;charset=UTF-8',
        //             'sec-fetch-dest': 'empty',
        //             'sec-fetch-mode': 'cors',
        //             'sec-fetch-site': 'same-site',
        //         },
        //         body: '{"mostraImpegniAnnullati":true,"mostraIndisponibilitaTotali":false,"linkCalendarioId":"6308e8ea0c34e703bb1f7e85","clienteId":"628de8b9b63679f193b87046","pianificazioneTemplate":false,"dataInizio":"2022-10-02T22:00:00.000Z","dataFine":"2022-10-07T22:00:00.000Z"}',
        //         method: 'POST',
        //         mode: 'cors',
        //         credentials: 'omit',
        //     }
        // )

        const request = fetch('/data.json')

        console.time('loading eventi')

        request
            .then(res => res.json())
            .then(data => {
                console.timeEnd('loading eventi')
                window.data = data
                setEventi(data)
            })
    }, [])

    const [mode, setMode] = useState('work-week-v')

    return (
        <>
            <Toolbar {...{ mode, setMode }} />
            <EventsView
                mode={mode}
                start={new Date(2022, 10, 3)}
                events={eventi.map(({ nome, dataInizio, dataFine, docenti, aule }) => ({
                    name: _.split(nome, '-', 1)[0].trim(),
                    start: new Date(dataInizio),
                    end: new Date(dataFine),
                    docenti: docenti.map(({ nome, cognome }) =>
                        _.startCase(_.lowerCase(nome) + ' ' + _.lowerCase(cognome))
                    ),
                    aula: _.startCase(aule[0].codice.toLowerCase()).replace(
                        /([A-Z]) ([1-9])/,
                        '$1$2'
                    ),
                }))}
            />
        </>
    )
}

render(<App />, document.body)
