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

import { useAppSelector, useAppDispatch } from '../../app/hooks';
import { RadioState, ConnectionState } from '../../app/types';
import {
    setRadioStarted,
    setRadioStopped,
    toggleRadioState,
    setConnected,
    setDisconnected,
    toggleConnection,
    selectLoading,
    selectRadio,
    selectConnection,
} from './radioSlice';
import {
    getOnWSOpen,
    getOnWSClose,
    getOnWSMessage,
} from './radioWS';

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 loadingState = 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) {
            onWSMessage(lastJsonMessage);
        }
    });

    if (loadingState) {
        return <div>Loading...</div>;
    }

    return (
        <div>
            <div>
                <button
                    aria-label="toggle-radio-state"
                    onClick={() => dispatch(toggleRadioState())}
                >TOGGLE</button>
                <div>Radio: {radioState}</div>
                <div>Connection: {connectionState}</div>
            </div>
        </div>
    );
}
