<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body{
        padding:0;
        margin:0;
        background-repeat: no-repeat;
        background-size:contain;
        background-position: center;
        height: 100vh;
        background-color: #4b444b;
    }
    @media (height < 700px) {
        body {
            height: 88vh;
        }
    }
        #top_bar {
            background-color: #6e84a3;
            color: white;
            font: bold 24px Helvetica;
            padding: 6px 5px 4px 5px;
            border-bottom: 1px outset;
        }

        #status {
            text-align: center;
        }
  </style>
  <script>
            function createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";               
        
            document.cookie = name + "=" + value + expires + "; path=/";
        }
        
        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }
        
        function eraseCookie(name) {
            createCookie(name, "", -1);
        }
        
        
        function readQueryVariable(name, defaultValue) {
            // A URL with a query parameter can look like this:
            // https://www.example.com?myqueryparam=myvalue
            //
            // Note that we use location.href instead of location.search
            // because Firefox < 53 has a bug w.r.t location.search
            const re = new RegExp('.*[?&]' + name + '=([^&#]*)'),
                  match = document.location.href.match(re);
        
            if (match) {
                // We have to decode the URL since want the cleartext value
                return decodeURIComponent(match[1]);
            }
        
            return defaultValue;
        }
        
        function uuidv4() {
        return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c =>
            (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)
        );
        }
        
        let uuid = readCookie("uuid")
        if (uuid==null){
            uuid = uuidv4();
            createCookie("uuid",uuid)   
        }
    function status(text) {
        document.getElementById('status').textContent = text;
    }
    window.onload = () => {
        if ('WebSocket' in window) {
            let was_connect = false;
            // create websocket connection
            let ws = null;
            con()

            function con(){
                ws = new WebSocket('wss://n0r.su/screen_share/ws');
                ws.onopen = () => {
                    console.log('websocket success---');
                    get()
                }
                ws.onclose = (e) => {
                    no_stream();
                    setTimeout(()=>{con()},5000)
                };
                ws.onerror = (e) => {
                    // setTimeout(()=>{con()},5000)
                    no_stream();
                    // console.error('websocket fail');
                }
            }
            function get() {
                ws.send(`get_stream%uuid=${uuid}`);
                // setTimeout(() => {
                //     get();
                // }, 100);
                ws.onmessage = (message) => {
                    if (message.data == "freeze"){
                        no_stream(true);
                        setTimeout(()=>{get();},2000)
                    }
                    else{
                        if (message.data != "null"){
                            was_connect = true;                    
                            let data = message.data;
                            // console.log('get websocket message---', JSON.parse(data)[1]);
                            document.body.style.backgroundImage = `url(data:image/jpeg;base64,${JSON.parse(data)[1]})`;
                            document.getElementById("top_bar").setAttribute("hidden","");
                            status("conected")
                            setTimeout(()=>{get()},200)
                        }
                        else{
                            setTimeout(()=>{get();},5000)
                            no_stream();
                        }
                    }
                }
            }
            ws.onerror = (e) => {
                // setTimeout(()=>{con()},5000)
                no_stream();
                        // console.error('websocket fail');
            }
            ws.onclose = (e) => {
                setTimeout(()=>{con()},5000)
                no_stream()
                // console.log("The connection has been closed successfully.")
            };

            function no_stream(freeze = false){
                if (!freeze){
                    if (document.body.style.backgroundImage != `url(/papi/savehouse/?const=club_dance)`){
                        document.body.style.backgroundImage = `url(/papi/savehouse/?const=club_dance)`;
                    }
                    document.getElementById("top_bar").removeAttribute("hidden");
                    if(was_connect){
                        status("Stream has ended")
                    }
                    else{
                        status("Stream is closed")
                    }
                }
                else{
                    document.getElementById("top_bar").removeAttribute("hidden");
                    status("stream is frozen")
                }
            }
        } else {
            console.error('dont support websocket');
        };
    };
</script>

</head>
<body>
    <div id="top_bar">
        <div id="status">Loading</div>
    </div>
</body>
</html>
