{% extends "AppBundle::template_live.html.twig" %} 

{% block stylesheets %}
{{ parent() }}
<style>
.panel { opacity: 1; }
</style>
{% endblock %}

{% block content %}
{% if navbarOnly is not defined %}
<div class="container-fluid">
    <div class="row"  id="live-tournament-overview">
       {% include "AppBundle:Live:content_chips.html.twig" %}
        
       {% include "AppBundle:Live:content_ranking.html.twig" %}        
    </div> 
</div>
{% endif %}
{% endblock %}

{% block footer %}
<footer class="footer">
  <div class="container">
    <div class="row">
        <div class="col-sm-8">
            
        </div>
    </div>
  </div>
</footer>

{% endblock footer %}

{% block javascripts %}
{{ parent() }}
<script>
var timeString = "";
var currStatus = "";
var clock_refresh;
var countdown_refresh;
var auto_refresh;
var ranking_refresh;

function refreshTournamentInfo()
{
	$.ajax({
        url: '{{ path('ajax_tournament_live_data', {'id': tournament.id }) }}',
        dataType: 'json',
        type: 'POST',
        success:function(data){
            console.info(data);
            console.info($.inArray(data.status, ["", "created"]));
           
            var nextBlindTime = $.now() - data.blind.next_time;

            $('#player_count').html(data.player.current + "/" + data.player.count);
            $('.current-blind').html(data.blind.current);
            $('.next-blind').html(data.blind.next);

            timeString = data.blind.raiseAt;
            // check time
            // todo: zeitumstelung? irgendwas stimmt da nicht, if wird nicht true....
            // FIX für 16. BPN: Bei Zeitumtellung wird der Blind neu gesetzt und damit auch die Zeiten
            if(timeString !== "" && new Date() >= new Date(timeString))
            {
            	$('.time-left').text('00:00:00').removeClass('text-success').addClass('text-danger blink_me');
                $('.time-left').parent().find('i').addClass('text-danger blink_me');
                
                 stopTimers();
                // play sound
                var times = 3;
                var loop = setInterval(repeat, 2020);
        
                function repeat() {
                    times--;
                    if (times === 0) {
                        clearInterval(loop);
                        loop = null;
                    }

                    $('.time-left').text('00:00:00');
                    var audio = document.createElement("audio");
                    audio.src = "{{ asset('bundles/app/audio/next_blind.mp3') }}";
        
                    audio.play();
                }
        
                repeat();  
               
                // start dmx
                $.ajax({
                    url: "{{ path('dmx_next_blind') }}",
                    success: function()
                    {
                    	$('.time-left').text('00:00:00');
                        // raise blind
                        $.ajax({
                            url: "{{ path('live_raise_blind', { 'tournamentId': tournament.id }) }}",
                            success: function()
                            {                                
                                setTimeout(function(){
                                	$('.time-left').removeClass('text-danger blink_me').addClass('text-success');
                                    $('.time-left').parent().find('i').removeClass('text-danger blink_me');                           
                                }, 5000);
                                
                                updateBlindCountdown();
                                startTimers();
                            }
                        });                        
                    }
                });
            }
        },
        error: function()
        {
            console.log("error");
            return;
        }
    });
}
{% if navbarOnly is not defined %}
function refreshRanking()
{
	$.ajax({
        url: '{{ path('ajax_tournament_ranking', {'id': tournament.id }) }}',
        dataType: 'json',
        type: 'POST',
        success:function(data){
            $('#player-ranking').empty();

            var i = 0;
            var item;
            var append = "";
            var length = data.length;
            
            for(j = 1; j <= 2; j++)
            {
            	add = "";
                while(i < (length / 2))
                {
                    item = data.pop();
                    if(typeof item != "undefined")
                    {
                    	add += "<li class=\"list-group-item\"><span class=\"label label-danger label-as-badge\">" + item.rank + "</span> " + item.player;

                    	if(item.kickedBy)
                    	{
                    	 add += " <small><small>vs. " + item.kickedBy + "</small> <span class=\"pull-right\"><small>" + item.kickedAt + "</small></span></small></li>";
                    	}
                    }
                    i++;
                }
                append += "<ul class=\"list-group borderless col-sm-6\">" + add + "</ul>";
                i = 0;
            }
            $('#player-ranking').append(append);
        }
    });
}
{% endif %}

function updateClock ()
{
    var currentTime = new Date ( );
    var currentHours = currentTime.getHours ( );
    var currentMinutes = currentTime.getMinutes ( );
    var currentSeconds = currentTime.getSeconds ( );
    
    // Pad the minutes and seconds with leading zeros, if required
    currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
    currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
   
    // Compose the string for display
    var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds;    
    $(".current-time").html(currentTimeString);       
}

function updateBlindCountdown()
{
	if(timeString == "")
	{
        $(".time-left").html("Waiting...");
		return;
	}
	var nextDate = new Date(timeString);
	nextDate = new Date(nextDate - new Date());

	var nextMinutes = nextDate.getMinutes ( );
    var nextSeconds = nextDate.getSeconds ( );

    // Pad the minutes and seconds with leading zeros, if required
    nextMinutes = ( nextMinutes < 10 ? "0" : "" ) + nextMinutes;
    nextSeconds = ( nextSeconds < 10 ? "0" : "" ) + nextSeconds;
   
    // Compose the string for display
    var nextTimeString =  " 00:" + nextMinutes + ":" + nextSeconds;    
    $(".time-left").html(nextTimeString);
}

function startTimers()
{
    //updateClock();
    refreshTournamentInfo();
    refreshRanking();

    //clock_refresh = setInterval('updateClock()', 1000);
    countdown_refresh = setInterval('updateBlindCountdown()', 1000);
    auto_refresh = setInterval('refreshTournamentInfo()', 10000);
    ranking_refresh = setInterval('refreshRanking()', 15000);
}

function stopTimers()
{
	//clearInterval(clock_refresh);
	clearInterval(countdown_refresh);
	clearInterval(auto_refresh);
	clearInterval(ranking_refresh);
}

$(document).ready(function()
{
	clock_refresh = setInterval('updateClock()', 1000);
	refreshTournamentInfo();
	auto_refresh = setInterval('refreshTournamentInfo()', 10000);
	startTimers();

    // Make the DIV element draggable:
    dragElement(document.getElementById("widget-live-ranking"));
    dragElement(document.getElementById("widget-live-chips"));
});

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "-header")) {
    // if present, the header is where you move the DIV from:
    document.getElementById(elmnt.id + "-header").onmousedown = dragMouseDown;
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
</script>
{% endblock %}
