import React from "react";

const ROOM_URL = 'http://localhost:5062/room';

const Home = () => {

    const [rooms, setRooms] = React.useState<string[]>([]);

    React.useEffect(() => {
        fetch(ROOM_URL)
            .then((r) => {
                console.log(r);
                return r.json();
            })
            .then((data) => {
                console.log(data);
                setRooms(data);
            });
    }, []);

    const handleCreateRoom = () => {
        fetch(ROOM_URL, {
            method: 'POST',
        }).then(r => r.json()).then(data => {
            setRooms([...rooms, data]);
        });
    }

    const gotoRoom = (roomId: string) => {
        window.location.href = `/room/${roomId}`;
    }

    return (
        <div>
            <button onClick={handleCreateRoom}>Create Room</button>
            <ul>
                {
                    rooms.map((room, index) => {
                        return <li key={index} onClick={() => gotoRoom(room)}>{room}</li>
                    })
                }
            </ul>
        </div>
    );
}

export default Home;
