import React, {useEffect, useRef, useState} from "react";
import {Row} from "antd";
import NextShot from "./components/NextShot";
import Feed from "./components/Feed";
import ShotsTaken from "./components/ShotsTaken";
import Lobby from "./components/Lobby";
import {useSocket} from "use-socketio";
import logo from "./via-logo.svg";
import {Tick} from "./types/types";
import {NumberParam, useQueryParam} from "use-query-params";

const Wrapper = () => {
    const [started, setStarted] = useState(false);
    const [wantsToStart, setWantsToStart] = useState(false);
    const player = useRef(new Audio("centurion.m4a"));
    const [noSound] = useQueryParam('noSound', NumberParam);

    function goStart() {
        console.log("Starting from wrapper..");
        setWantsToStart(true);
    }


    const {socket} = useSocket("started", async (obj: any) => {
        console.log("got started");
        setStarted(true);

        if (typeof noSound === 'undefined') {
            await player.current.play();
        }
    });

    useEffect(() => {
        if (noSound === 1) {
            // Won't play sound so we don't get DOM Interaction errors.
            setWantsToStart(true);
        }
    }, []);

    useSocket("tick_event", async (tick: Tick) => {
        if (!started && wantsToStart) {
            if (player.current.paused) {
                if (typeof noSound === 'undefined') {
                    await player.current.play();
                }
            }

            setStarted(true);
            player.current.currentTime = tick.current;
        }
    });

    const feedContent = (
        <Row>
            <NextShot/>
            <Feed/>
            <ShotsTaken/>
        </Row>
    );

    const lobbyContent = (
        <Lobby start={goStart}/>
    );

    const content = started ? feedContent : lobbyContent;

    return (
        <>
            <section className="content">
                {content}
            </section>
            <footer>
                <img src={logo} className="via-logo" alt="logo"/>
            </footer>
        </>
    );
};

export default Wrapper;