import React, {useEffect, useRef, useState} from 'react';
import {Col, Progress} from "antd"
import socket from "../util/socket";
import {Tick} from "../types/types";


const NextShot = () => {
    const [remaining, setRemaining] = useState(60);
    const [remainingPercentage, setRemainingPercentage] = useState(100);
    const fullTime = useRef(0);

    useEffect(() => {
        socket.on("tick_event", (tick: Tick) => {
            if (!tick.nextShot || !tick.next) {
                setRemaining(0);
                return;
            }

            if (fullTime.current === 0) {
                fullTime.current = tick.nextShot.timestamp - tick.current;
            }

            const shotEvent = tick.next.events.find(e => e.type === 'shot');

            if (shotEvent && tick.current === tick.next.timestamp) {
                fullTime.current = 0;
            }

            const timeRemaining = tick.nextShot.timestamp - tick.current;

            setRemaining(timeRemaining);
            // Fix divide by zero (.. || 1)
            setRemainingPercentage(Math.ceil(timeRemaining / (fullTime.current || 1) * 100));
        });

        return () => {
            socket.off("tick_event");
        }
    }, []);

    return (
        <Col className="sider" span={4}>
            <h1>Tijd tot volgende shot:</h1>
            <Progress type="circle"
                      percent={remainingPercentage}
                      format={_ => remaining + ' sec.'}
                      strokeColor={"#304ba3"}
                      strokeWidth={10}
                      status="normal"/>
        </Col>

    );
};

export default NextShot;
