<!DOCTYPE html>

<head>
    <title>Room: <%=roomId%>
    </title>
    <script src="/socket.io/socket.io.js"></script>
</head>
<html>

<body>
    <input id="link" type="text">
    <input id="submit" type="submit">

    <div id="videoContainer">
        <div id="player"></div>
    </div>
    
    <script type="module">

        import Video from '/./model/video.js';
        console.log(new Video())

        
        var myRoomId = '<%=roomId%>';
        const socket = io.connect(`${'<%=URL%>'}/room/${myRoomId}`, { auth: { roomId: myRoomId } }); // Our server.js portnumber
        let currentVideoId = "<%=videoId%>"
        let userId = ( Math.random()*2222222 ) | 0;

        /*socket.on('connect', ()=>{
            console.log('connected!');

        })
        socket.on('message', (msg) => {
            console.log(msg)
        })*/

        var tag = document.createElement('script');

        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
        var bool_flag_1 = false;

        var player;
        window.onYouTubeIframeAPIReady = function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
                height: '390',
                width: '640',
                videoId: "<%=videoId%>",
                playerVars: {
                    'playsinline': 1
                },
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': (event) => {
                        if(is_coming_time){
                            is_coming_time = false;

                            return;
                        }
                        console.log('mytime')
                        console.log(player.getCurrentTime());
                        if (event.data == YT.PlayerState.PLAYING || event.data == YT.PlayerState.UNSTARTED || event.data == YT.PlayerState.BUFFERING) {
                            console.log('başlattın')
                            socket.emit('statusChanged', 1, myRoomId)
                            /*if(bool_flag_1)
                                socket.emit('getTime', myRoomId, userId)*/
                        }
                        else {
                            socket.emit('statusChanged', 0, myRoomId);
                        }
                        if (Math.abs(lastTime - player.getCurrentTime()) > 2) {
                            console.log('Seeked!')
                            console.log(player.getPlayerState());
                            let time = player.getCurrentTime();
                            socket.emit('clientSeek', time);
                            lastTime = time;
                        }
                    }
                }
            });
        }

        var is_coming_time = false;
        socket.on('comingTime', (uid, time)=>{
            if(uid != userId)return;
            is_coming_time = true;
            player.seekTo(time, true);
        })

        socket.on('handleStatus', (status) => {
            if (status == 0) {
                player.pauseVideo();
            }
            else if (status == 1) {
                player.playVideo();
            }
        })



        var lastTime = 0;
        function onPlayerReady(event) {
            setTimeout(() => event.target.playVideo(), 100);
            setInterval(() => {
                if(player.getPlayerState()==2)return;
                let time = player.getCurrentTime();
                socket.emit("currentTime", time, currentVideoId, myRoomId)
                bool_flag_1 = true;
                lastTime = time;
            }, 250)
            socket.emit('init', myRoomId);
        }


        socket.on('seek', (time, status, vidId) => {
            //player.loadVideoById(vidId, time);
            window.history.pushState("", "", vidId);
            player.seekTo(time);
            if (status == 0) {
                player.pauseVideo();
            }
            else if (status == 1) {
                player.playVideo();
            }
            currentVideoId = vidId;
        })

        socket.on('clientVideoChange', (link, time) => {
            player.loadVideoById(link);
            window.history.pushState("", "", link);
        })

        socket.on('timeChanged', (time) => {
            console.log('Time change isteği alındı!')
            player.seekTo(time);
        })



        submit.onclick = () => {
            let link = document.getElementById("link").value;
            let submit = document.getElementById("submit");
            link = link.substring(link.lastIndexOf("=") + 1, link.length)
            currentVideoId = link;
            socket.emit('videoChange', link, myRoomId);
            player.loadVideoById(link);
            window.history.pushState("", "", link);
        }

    </script>
</body>

</html>