<!--
Copyright (C) 2023 Stefy Lanza <stefy@nexlab.net> and SexHack.me

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Streaming Control Panel</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body, html {
            height: 100%;
            font-family: Arial, sans-serif;
            overflow: hidden;
        }

        .main-container {
            display: flex;
            height: 100vh;
            width: 100vw;
        }

        .buttons-container {
            display: grid;
            grid-template-columns: repeat(120, 1fr);
            grid-template-rows: repeat(4, 1fr);
            height: 100%;
            width: 100%;
        }

        .button_row {
            display: grid;
            grid-template-columns: repeat(120, 1fr);
            width: 100%;
            grid-column: span 120;
        }

        {{style_rows|safe}}

        .button {
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1.5vw;
            font-weight: bold;
            text-align: center;
            border: 2px solid white;
            cursor: pointer;
            transition: all 0.3s ease;
            text-transform: uppercase;
        }

        /* Color variations */
        .private { background-color: #4CAF50; color: white; }
        .toggle { background-color: #2196F3; color: white; }
        .special { background-color: #FF9800; color: white; }

        .button:hover {
            opacity: 0.8;
            transform: scale(1.05);
        }

        .button:active {
            background-color: #45a049;
            transform: scale(0.95);
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .button {
                font-size: 3vw;
            }
        }
    </style>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
     <script src="https://cdn.socket.io/4.7.5/socket.io.min.js" integrity="sha384-2huaZvOR9iDzHqslqwpR87isEmrfxqyWOF7hr7BY6KG0+hVKLoEXMPUJw3ynWuhO" crossorigin="anonymous"></script>
</head>
<body>
    <div class="main-container">
        <!-- Buttons Container -->
        <div class="buttons-container">
           {{htmlbuttons|safe}}
        </div>
    </div>

    <script>
        function executeCommand(command) {
            fetch('/execute', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `command=${command}`
            })
            .then(response => response.text())
            .then(result => {
                console.log(result);
                // Visual feedback
                /*event.target.style.backgroundColor = '#45a049';
                setTimeout(() => {
                    event.target.style.backgroundColor = 
                        event.target.classList.contains('private') ? '#4CAF50' :
                        event.target.classList.contains('toggle') ? '#2196F3' :
                        '#FF9800';
                }, 300); */
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        // Prevent zoom on double-tap for mobile
        document.addEventListener('touchmove', function(event) {
            if (event.scale !== 1) { event.preventDefault(); }
        }, { passive: false });

        $(document).ready(function() {
            // Connect to the Socket.IO server.
            // The connection URL has the following format, relative to the current page:
            //     http[s]://<domain>:<port>[/<namespace>]
            var socket = io();

            // Event handler for new connections.
            // The callback function is invoked when a connection with the
            // server is established.
            socket.on('connect', function() {
                socket.emit('my_event', {data: 'I\'m connected!'});
            });

            // Event handler for server sent data.
            // The callback function is invoked whenever the server emits data
            // to the client. The data is then displayed in the "Received"
            // section of the page.
            socket.on('my_response', function(msg, cb) {
                $('#log').append('<br>' + $('<div/>').text('Received #' + msg.count + ': ' + msg.data).html());
                if (cb)
                    cb();
            });

            // Interval function that tests message latency by sending a "ping"
            // message. The server then responds with a "pong" message and the
            // round trip time is measured.
            var ping_pong_times = [];
            var start_time;
            window.setInterval(function() {
                start_time = (new Date).getTime();
                $('#transport').text(socket.io.engine.transport.name);
                socket.emit('my_ping');
            }, 1000);

            // Handler for the "pong" message. When the pong is received, the
            // time from the ping is stored, and the average of the last 30
            // samples is average and displayed.
            socket.on('my_pong', function() {
                var latency = (new Date).getTime() - start_time;
                ping_pong_times.push(latency);
                ping_pong_times = ping_pong_times.slice(-30); // keep last 30 samples
                var sum = 0;
                for (var i = 0; i < ping_pong_times.length; i++)
                    sum += ping_pong_times[i];
                $('#ping-pong').text(Math.round(10 * sum / ping_pong_times.length) / 10);
            });

            window.setInterval(function() {
                socket.emit('get_queue');
            }, 200);

            socket.on('change_output', function(msg, cb) {
               //console.log('CHANGE OUTPUT');
               //console.log(msg);
               $('.output_'+msg.button).css('background-color', msg.color);
            });

            socket.on('change_input', function(msg, cb) {
               $('.input_'+msg.button).css('background-color', msg.color);
            });


           socket.on('change_feedback', function(msg, cb) {
               if(msg.hasOwnProperty("color")) 
                    $('.feedback_'+msg.feedback).css('background-color', msg.color);
               if(msg.hasOwnProperty("title"))
                   $('.feedback_'+msg.feedback).text(msg.title);
           });

        });
    </script>
    <div id="log"></div>
    <div id="ping-pong"></div>ms</b>
    <div id="transport"></div>
 </body>
</html>