import React, { useEffect } from 'react';
import useWebSocket from 'react-use-websocket';

import { useAppSelector, useAppDispatch } from '../../app/hooks';
import { RadioState, ConnectionState } from '../../app/types';
import {
    toggleRadioState,
    selectLoading,
    selectRadio,
    selectConnection,
} from './radioSlice';
import {
    getOnWSOpen,
    getOnWSClose,
    getOnWSMessage,
} from './radioWS';
import styles from './Radio.module.scss';

const getWSUrl = async () => {
    const wsUrl = process.env.WS_ADDR ? process.env.WS_ADDR : "ws://localhost/liveness";
    console.log("WS ADDR: %s", wsUrl);
    return wsUrl;
};

export function RadioToggler() {
    const loading = useAppSelector(selectLoading);
    const radioState = useAppSelector(selectRadio);
    const connectionState = useAppSelector(selectConnection);

    const dispatch = useAppDispatch();

    const { lastJsonMessage } = useWebSocket(getWSUrl,
        {
            onOpen: getOnWSOpen(dispatch),
            onClose: getOnWSClose(dispatch),
        });

    const onWSMessage = getOnWSMessage(dispatch);
    useEffect(() => {
        if (lastJsonMessage != null) {
            if (!loading) {
                onWSMessage(lastJsonMessage);
            }
        }
    }, [lastJsonMessage]);

    let buttonStatus = "";
    let circleStyle = styles.circleDisconnected;
    if (loading) {
        buttonStatus = "Loading";
        circleStyle = styles.circleLoading;
    } else if (connectionState) {
        switch (radioState) {
            case RadioState.STARTED:
                buttonStatus = "ON AIR";
                circleStyle = styles.circleStarted;
                break;
            case RadioState.STOPPED:
                buttonStatus = "OFFLINE";
                circleStyle = styles.circleStopped;
                break;
        }
    }

    return (
        <div>
            <div className={styles.buttonWrap} aria-label="toggle-radio-state">
                <div
                    className={styles.clicker}
                    onClick={() => dispatch(toggleRadioState())}
                >{buttonStatus}</div>
                <div className={circleStyle}></div>
            </div>
        </div >
    );
}
