{% extends "base.html" %}
{% load i18n %}
{% load l10n %}
{% load staticfiles %}
{% load wger_extras %}
{% load cache %}

{% block title %}{% endblock %}

{% block header %}
<style>

</style>
<script>
"use strict";
/*
 * http://fearlessflyer.com/how-to-create-your-own-jquery-content-slider/
 * https://github.com/fearlessflyer/content-slider
 * http://irae.pro.br/lab/canvas_pie_countdown/
 * http://www.html5canvastutorials.com/tutorials/html5-canvas-arcs/
 * http://bookofzeus.com/articles/build-a-fancy-countdown-with-html5
 */

var div_height = $( window ).height() * 0.80;
var div_width = $( window ).width() * 0.85;
var start = new Date();

var counter = {

    // counters (in seconds, except the milliseconds one)
    start: 0,
    end: 60,
    seconds: 0,
    milliseconds: 0,

    // other
    fps: 40,
    step_id: '',
    interval: 0,

    // Canvas info
    ctx: '',
    canvas_size: [0, 0],
    radius: 75,
    center: 75,

    draw_step: function(){
        /*
         * Step function, called every 1000/fps ms
         */

        // Perform exit cleanup if we finish the countdown
        if (this.milliseconds >= this.end * 1000)
        {
            clearInterval(this.interval);
            $('#counter-' + this.step_id).html('0');

            var step = $('li[data-step="' + this.step_id + '"]');
            paginate_to(step.data('number') + 1);
            return;
        }

        // Update the HTML element with the current remaining time once per second
        if (this.seconds != Math.ceil(this.milliseconds/1000))
        {
            $('#counter-' + this.step_id).html(this.end - this.seconds);
        }

        // Draw the arc in the canvas element
        var step = this.milliseconds / (this.end * 1000) ;
        this.ctx.clearRect(0, 0, this.canvas_size[0], this.canvas_size[1]);
        this.ctx.beginPath();
        this.ctx.moveTo(this.center[0], this.center[1]);
        this.ctx.arc(
            this.center[0],
            this.center[1],
            this.radius,
            Math.PI * -0.5,
            Math.PI * (-0.5 + step*2),
            true // anti clockwise
        );
        this.ctx.lineTo(this.center[0], this.center[1]); // line back to the center
        this.ctx.closePath();
        this.ctx.fillStyle = 'rgb(40, 40, 40)'; // color
        this.ctx.fill();

        // Update counters
        this.seconds = Math.ceil(this.milliseconds/1000);
        this.milliseconds = this.milliseconds + 1000/this.fps;
    },

    init_canvas: function(step_id, seconds){
        /*
         * Initialise the canvas
         */
        var canvas = document.getElementById('canvas-div-' + step_id);
        this.ctx = canvas.getContext('2d');
        this.canvas_size = [canvas.width, canvas.height];
        this.radius = Math.min(this.canvas_size[0], this.canvas_size[1]) / 2;
        this.center = [this.canvas_size[0]/2, this.canvas_size[1]/2];
    }
}


function start_countdown(step_id, seconds)
{
    /*
     * Initialise the counter objects and start the interval
     */
    counter.start = 0;
    counter.end = seconds;
    counter.milliseconds = 0;
    counter.seconds = 0;
    counter.step_id = step_id;

    counter.init_canvas(step_id, seconds);
    counter.interval = setInterval(
        function() { counter.draw_step(step_id, seconds); },
        1000/counter.fps
    );
}

function paginate_to(index){
    /*
     * Paginate to the step page with the given index
     */
    $('ul#workout-timer').animate({
        "margin-left": (-index * div_width)
    }, 600)
}


$(document).ready(function() {

    $('#page-title').remove();

    $('.timer-step').width(div_width);
    $('.timer-step').height(div_height);

    //wrap into mother div
    $('#timer-container ul').wrap('<div id="mother" />');

    //assign height width and overflow hidden to mother
    $('#mother').css({
        width: function() {
            return div_width;
        },
        height: function() {
            return div_height;
        },
        position: 'relative',
        overflow: 'hidden'
    });

    //get total of image sizes and set as width for ul
    var totalWidth = $('.timer-step').length * div_width;
    $('#timer-container ul').css({
        width: function() {
            return totalWidth;
        }
    });

    // Bind the buttons that create new logs
    $('.save_log').bind("click", function(e) {
        e.preventDefault();
        var step_id = $(this).parents('li').data('step');
        var form = $('#form-' + step_id);

        $.post( form.attr('action'), form.serialize(), function(data) {
                 //response
               }
        );
    });

    // Bind the timer +/- buttons
    //timer-minus
    $('.timer-minus').bind("click", function(e) {
        e.preventDefault();
        counter.end = counter.end - 10;
    });
    $('.timer-plus').bind("click", function(e) {
        e.preventDefault();
        counter.end = counter.end + 10;
    });

    // Bind the pagination buttons
    $('#timer-container ul li.timer-step a.next').bind("click", function(e) {
        e.preventDefault();
        var step_id = $(this).parents('li').data('step');
        var step_time = $(this).parents('li').data('time');
        var step_nr = $(this).parents('li').data('number');

        //Cancel any previously running countdowns
        clearInterval(counter.interval);

        // Paginate to next step
        paginate_to(step_nr + 1)

        // Start the countdown for the next step slightly after the previous
        // pagination animation is finished
        var next_step = $(this).parents('li.timer-step').next();
        if (next_step.is('.pause-step'))
        {
            setTimeout(function() {
               start_countdown(next_step.data('step'), next_step.data('time'));
            }, 700);
        }

        // If we have reached the last page, compute total workout time
        if (next_step.is('#workout-complete'))
        {
            var end = new Date();
            var milliseconds = (end.getTime() - start.getTime());

            var hours = (milliseconds/1000) / 3600;
            var minutes = (milliseconds/1000) / 60 - Math.floor(hours)*60;
            var seconds = milliseconds/1000 - Math.floor(minutes)*60 - Math.floor(hours)*3600;

            hours = (hours < 10) ? '0' + hours : hours;
            minutes = (minutes < 10) ? '0' + minutes : minutes;
            seconds = (seconds < 10) ? '0' + seconds : seconds;

            //a.toLocaleTimeString()
            $('#total_time').html(Math.floor(hours) + ':' + Math.floor(minutes) + ':' + Math.floor(seconds));

            $('#id_time_start').val(start.getHours() + ':' + start.getMinutes());
            $('#id_time_end').val(end.getHours() + ':' + end.getMinutes());
            $('#id_date').val(end.getFullYear() + '-' + end.getMonth() + '-' + end.getDay());
            $('#id_user').val('1');
        }

    });

    // Bind the button to save the workout session form
    $('#save_button_form').bind("click", function(e) {
        e.preventDefault();
        $.post( $('#session-form').attr('action'),
                $('#session-form').serialize(),
                
                // After clicking on the save button once, disable it
                function( data ) {
                    var today = new Date();
                    var date = '/' + today.getFullYear() + '/' + (today.getMonth() + 1) + '/' + today.getDate();
                    window.location = '/' + get_current_language() + '/workout/calendar/' + get_username() + date;
                    $('#save_button_form').unbind("click");
                    $('#save_button_form').addClass('disabled');
                    $('#save_button_form').bind("click", function(e) {
                        e.preventDefault();
                    });
                });
        });
});
</script>
{% endblock %}

{% block content %}
{#            #}
{# Start page #}
{#            #}
<div id="timer-container" style="position: relative; margin:0px; padding: 0px;">
<ul id="workout-timer">
<li class="timer-step" id="div-warmup" data-number="0">
    <h2>{% trans "Your workout today" %}</h2>

    <div class="filler_div">
        {% for set in canonical_day.set_list %}
            {% for exercise in set.exercise_list %}
                {{exercise.obj}}: {{exercise.setting_text}}<br>
            {% endfor %}
        {% endfor %}
    </div>

    <a class="next bottom_button wide_link btn btn-primary"
       href="#">{% trans "Start!" %}</a>
</li>

{% for step in step_list %}
    {#               #}
    {# exercise page #}
    {#               #}
    {% if step.type == 'exercise' %}
        <li class="timer-step exercise-step"
            id="div-{{step.current_step}}"
            data-step="{{step.current_step}}"
            data-number="{{step.step_nr}}">
            <h2>{{step.exercise}}</h2>
            <form action="{% url 'manager:log:add' workout.pk %}"
                  method="POST"
                  id="form-{{step.current_step}}">
                {% csrf_token %}
                <input name="exercise"
                       id="id-exercise-{{step.current_step}}"
                       value="{{step.exercise.pk}}"
                       type="hidden">
                <input name="date"
                       id="id-date-{{step.current_step}}"
                       value="{% now 'Y-m-j' %}"
                       type="hidden">
            <div class="row filler_div">
                <div class="col-xs-6">
                    <label for="id-reps-{{step.current_step}}">{% trans "Repetitions" %}:</label>
                    <input name="reps"
                           id="id-reps-{{step.current_step}}"
                           placeholder="{% trans 'Repetitions' %}"
                           value="{{step.reps}}"
                           type="number"
                           autocomplete="off"
                           class="form-control">
                </div>
                <div class="col-xs-6">
                    <label for="id-weight-{{step.current_step}}">{% trans "Weight" %}:</label>
                    <input name="weight"
                           id="id-weight-{{step.current_step}}"
                           placeholder="{% trans 'Weight' %}"
                           value="{{step.weight|unlocalize}}"
                           type="number"
                           autocomplete="off"
                           class="form-control">
                </div>
            </div>
            </form>

            <div class="sub_header">
                <h2>
                {% if step.weight %}
                    {{step.reps}} × {{step.weight}} {% trans_weight_unit 'kg' user %}
                {% else %}
                    {% if step.reps == 99 %}∞{% else %}{{step.reps}}{% endif %} {% trans "reps" %}
                {% endif %}
                </h2>
            </div>

            <div class="row bottom_buttons">
                <div class="col-xs-6">
                    <a class="next wide_link btn btn-default"
                       href="#"><!-- {% trans "Skip" %}--> <span class="glyphicon glyphicon-forward"></span>
                    </a>
                </div>
                <div class="col-xs-6">
                    <a class="next save_log wide_link btn btn-success"
                       href="#">{% trans "Save" %} <span class="glyphicon glyphicon-save"></span></a>
                </div>
            </div>


            <div id="progress-{{step.current_step}}" class="progress-bar">
                <span style="width: {{step.step_percent|stringformat:'f'}}%;"></span>
            </div>
        </li>

    {#            #}
    {# pause page #}
    {#            #}
    {% else %}
        <li class="timer-step pause-step"
            id="div-{{step.current_step}}"
            data-time="{{step.time}}"
            data-step="{{step.current_step}}"
            data-number="{{step.step_nr}}">
            <h2>{% trans "Pause!" %}</h2>

            <div style="width: 96%; text-align: center;">
            <canvas id="canvas-div-{{step.current_step}}" width="150" height="150"></canvas>
            </div>


            <div class="row sub_header">
                <div class="col-xs-4">
                    <h2><span id="counter-{{step.current_step}}">{{step.time}}</span></h2>
                </div>
                <div class="col-xs-4">
                    <a class="start timer-plus btn btn-default"
                       href="#"
                       id="button-plus-{{step.current_step}}">+10</a>
                </div>
                <div class="col-xs-4">
                    <a class="start timer-minus btn btn-default"
                       href="#"
                       id="button-minus-{{step.current_step}}">-10</a>
                </div>
            </div>


            <a class="next bottom_button wide_link btn btn-default"
               href="#">{% trans "Skip" %} <span class="glyphicon glyphicon-forward"></span></a>

            <div id="progress-{{step.current_step}}" class="progress-bar">
                <span style="width: {{step.step_percent|stringformat:'f'}}%;"></span>
            </div>
        </li>
    {% endif %}
{% endfor %}

{#           #}
{# last page #}
{#           #}
<li class="timer-step" id="workout-complete">
    <h2>{% trans "Workout complete!" %}</h2>

    <div class="filler_div">
        <form action="{{ form_action }}" id="session-form">
            {% csrf_token %}
            {{ session_form.time_start }}
            {{ session_form.time_end }}
            {{ session_form.user }}


            <div class="modal fade" id="info-{{session_form.notes.auto_id}}">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                            <h4 class="modal-title">{% trans "Info" %}</h4>
                        </div>
                        <div class="modal-body">
                            {% trans session_form.notes.help_text %}
                        </div>
                    </div>
                </div>
            </div>

            <label for="{{session_form.notes.auto_id}}">
                <a href="#info-{{session_form.notes.auto_id}}"
                   class="btn btn-default btn-sm"
                   data-toggle="modal">
                    <span class="glyphicon glyphicon-asterisk"></span>
                   </a>
                {% trans session_form.notes.label %}
            </label>
            {{ session_form.notes|form_field_add_css:'form-control' }}

            <div class="modal fade" id="info-{{session_form.impression.auto_id}}">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                            <h4 class="modal-title">{% trans "Info" %}</h4>
                        </div>
                        <div class="modal-body">
                            {% trans session_form.impression.help_text %}
                        </div>
                    </div>
                </div>
            </div>
            <label for="{{session_form.impression.auto_id}}">
                <a href="#info-{{session_form.impression.auto_id}}"
                   class="btn btn-default btn-sm"
                   data-toggle="modal">
                    <span class="glyphicon glyphicon-asterisk"></span>
                   </a>
                {% trans session_form.impression.label %}
            </label>
            {{ session_form.impression|form_field_add_css:'form-control' }}

            <!--
            {% render_form_field session_form.notes %}
            {% render_form_field session_form.impression %}
            -->

        </form>
    </div>

    <div class="sub_header">
        <h2><strong>{% trans "Time" %}:</strong> <span id="total_time">MM:SS</span></h2>
    </div>

    <div class="row bottom_buttons">
        <div class="col-xs-6">
            <a href="{% url 'core:dashboard' %}"
               class="wide_link btn btn-default">{% trans "Dashboard" %}</a>
        </div>
        <div class="col-xs-6">
            <a href=""
               id="save_button_form"
               class="wide_link btn btn-success">
                {% trans "Save" %}
                <span class="glyphicon glyphicon-save"></span>
            </a>
        </div>
    </div>


    <div id="progress-{{step.current_step}}" class="progress-bar">
        <span style="width: 100%;"></span>
    </div>
</li>
</ul>
</div>
{% endblock %}



<!--
        Side bar
-->
{% block sidebar %}

{% endblock %}
