<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <title>RobotJS evaluation</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<style>
    html, body {
        height: 100%;
        margin: 0;
    }
    #panel {
        display: flex;
        height: 100%;
        background-color: gray;
    }
</style>
<body>
    <div id="panel"></div>
    <script type="text/javascript">
        // @ts-check
        const throttle = (mainFunction, delay) => {
            let timerFlag = null;
            return (...args) => {
                if (timerFlag === null) {
                    mainFunction(...args);
                    timerFlag = setTimeout(() => {
                        timerFlag = null;
                    }, delay);
                };
            };
        };

        const onMouseMove = event => {
            const rect = event.target.getBoundingClientRect();
            const message = {
                type: 'information',
                data: {
                    obj: 'mouse',
                    action: 'move',
                    payload: {
                        screen: {
                            height: rect.height,
                            width: rect.width,
                        },
                        mouseX: event.clientX - rect.left,
                        mouseY: event.clientY - rect.top,
                    }
                }
            };
            socket.send(JSON.stringify(message));
        };

        const onMouseDown = event => {
            const message = {
                type: 'information',
                data: {
                    obj: 'mouse',
                    action: 'click',
                    payload: {
                        direction: 'down',
                        button: event.button,
                    }
                }
            };
            socket.send(JSON.stringify(message));
        };

        const onMouseUp = event => {
            const message = {
                type: 'information',
                data: {
                    obj: 'mouse',
                    action: 'click',
                    payload: {
                        direction: 'up',
                        button: event.button,
                    }
                }
            };
            socket.send(JSON.stringify(message));
        };

        const MOUSE_MOVE_DELAY = 50;
        const streamElement = document.getElementById('panel');
        streamElement?.addEventListener('contextmenu', event => event.preventDefault());
        streamElement?.addEventListener('mousemove', throttle(onMouseMove, MOUSE_MOVE_DELAY));
        streamElement?.addEventListener('mousedown', onMouseDown);
        streamElement?.addEventListener('mouseup', onMouseUp);
        const socket = new WebSocket('ws://hpc.home/actor');
    </script>
</body>
</html>
