{% extends app.request.xmlHttpRequest ? 'form.html.twig' : 'base.html.twig' %}
{% import "macros/widgets.html.twig" as widgets %}

{% block main %}
    {% if timesheet.exported %}
        {{ widgets.alert('warning', ('timesheet.locked.warning'|trans({}, 'flashmessages')), ('warning'|trans({}, 'flashmessages')), 'warning') }}
    {% endif %}
    {% set formEditTemplate = app.request.xmlHttpRequest ? 'default/_form_modal.html.twig' : 'default/_form.html.twig' %}
    {% set formOptions = {
        'title': (timesheet.id ? 'timesheet.edit'|trans : 'create'|trans),
        'form': form,
        'back': path(route_back)
    } %}
    {% embed formEditTemplate with formOptions %}
        {% set length = 6 %}
        {% if form.begin is defined and form.end is defined and form.duration is defined %}
            {% set length = 5 %}
        {% elseif form.begin is defined and form.end is defined and form.duration is not defined %}
            {% set length = 6 %}
        {% elseif form.begin is defined and form.end is not defined and form.duration is defined %}
            {% set length = 10 %}
        {% elseif form.begin is not defined and form.end is defined and form.duration is defined %}
            {% set length = 10 %}
        {% endif %}
        {% block form_body %}
            {% if form.begin is defined or form.end is defined or form.duration is defined %}
            <div class="row">
                {% if form.begin is defined %}
                    <div class="col-md-{{ length }}">
                        {{ form_row(form.begin) }}
                    </div>
                {% endif %}
                {% if form.end is defined %}
                    <div class="col-md-{{ length }}">
                        {{ form_row(form.end) }}
                    </div>
                {% endif %}
                {% if form.duration is defined %}
                    <div class="col-md-2">
                        {{ form_row(form.duration) }}
                    </div>
                {% endif %}
            </div>
            {% endif %}
            {% if form.customer is defined %}
                {{ form_row(form.customer) }}
            {% endif %}
            {% if form.project is defined %}
                {{ form_row(form.project) }}
            {% endif %}
            {% if form.activity is defined %}
                {{ form_row(form.activity) }}
            {% endif %}
            {% if form.description is defined %}
                {{ form_row(form.description) }}
            {% endif %}
            {% if form.tags is defined %}
                {{ form_row(form.tags) }}
            {% endif %}
            {% if form.user is defined %}
                {{ form_row(form.user) }}
            {% endif %}
            {% if form.users is defined or form.teams is defined %}
                {% set uLength = 12 %}
                {% if form.users is defined and form.teams is defined %}
                    {% set uLength = 6 %}
                {% endif %}
                <div class="row">
                {% if form.users is defined %}
                    <div class="col-md-{{ uLength }}">
                        {{ form_row(form.users) }}
                    </div>
                {% endif %}
                {% if form.teams is defined %}
                    <div class="col-md-{{ uLength }}">
                        {{ form_row(form.teams) }}
                    </div>
                {% endif %}
                </div>
            {% endif %}
            {% if form.fixedRate is defined and form.hourlyRate is defined %}
            <div class="row">
                <div class="col-md-6">
                    {{ form_row(form.fixedRate) }}
                </div>
                <div class="col-md-6">
                    {{ form_row(form.hourlyRate) }}
                </div>
            </div>
            {% endif %}
            {{ form_widget(form) }}
        {% endblock %}
        {% block form_after %}
            {% if form.begin is defined and form.end is defined and form.duration is defined %}
                {% set blockPrefix = form.vars.id %}
                <script type="text/javascript">
                    $('body').on('blur change', '#{{ blockPrefix }}_begin', function(ev) {
                        changedBegin($(this).val());
                    });

                    $('body').on('blur change', '#{{ blockPrefix }}_end', function(ev) {
                        changedEnd($(this).val());
                    });

                    $('body').on('blur change', '#{{ blockPrefix }}_duration', function(ev) {
                        changedDuration($(this).val());
                    });
                    
                    {#
                        Ruleset: 
                        - invalid begin => skip
                        - empty end => set end to begin (only if duration > 0 = running record)
                        - invalid end => skip
                        - calculate duration 
                    #}

                    function changedBegin(value)
                    {
                        var endField = document.getElementById('{{ blockPrefix }}_end');
                        var durationField = document.getElementById('{{ blockPrefix }}_duration');
                        var format = endField.dataset.format;
                        var momentDuration = moment.duration(durationField.value);

                        var momentBegin = moment(value, format);
                        if (!momentBegin.isValid()) {
                            return;
                        }
                        
                        if (endField.value === '' && momentDuration.asSeconds() > 0) {
                            applyDateToField(endField, momentBegin, format);
                        }

                        var momentEnd = moment(endField.value, format);
                        if (!momentEnd.isValid()) {
                            return;
                        }
                        
                        if (momentEnd.isBefore(momentBegin)) {
                            applyDateToField(endField, momentBegin.add(momentDuration), format);
                        }

                        momentBegin = moment(value, format);
                        momentEnd = moment(endField.value, format);
                        
                        var durationMoment = moment.duration(momentEnd.diff(momentBegin));
                        var hours = Math.floor(durationMoment.asHours());
                        if (hours < 10) {
                            hours = '0' + hours;
                        }
                        
                        durationField.value = hours + ':' + ('0' + durationMoment.minutes()).slice(-2);
                    }

                    {#
                        Ruleset: 
                        - invalid end => skip
                        - empty begin => set begin to end
                        - invalid begin => skip
                        - calculate duration 
                    #}

                    function changedEnd(value)
                    {
                        var beginField = document.getElementById('{{ blockPrefix }}_begin');
                        var durationField = document.getElementById('{{ blockPrefix }}_duration');
                        var format = beginField.dataset.format;
                        var momentDuration = moment.duration(durationField.value);

                        var momentEnd = moment(value, format);
                        if (!momentEnd.isValid()) {
                            return;
                        }

                        if (beginField.value === '') {
                            applyDateToField(beginField, momentEnd, format);
                        }

                        var momentBegin = moment(beginField.value, format);
                        if (!momentBegin.isValid()) {
                            return;
                        }

                        if (momentEnd.isBefore(momentBegin)) {
                            applyDateToField(beginField, momentEnd.subtract(momentDuration), format);
                        }

                        momentBegin = moment(beginField.value, format);
                        momentEnd = moment(value, format);

                        var durationMoment = moment.duration(momentEnd.diff(momentBegin));
                        var hours = Math.floor(durationMoment.asHours());
                        if (hours < 10) {
                            hours = '0' + hours;
                        }
                        
                        durationField.value = hours + ':' + ('0' + durationMoment.minutes()).slice(-2);
                    }

                    {#
                        Ruleset: 
                        - invalid duration => skip
                        - if begin and end are empty: set begin to now and end to duration
                        - if begin is empty and end is not empty: set begin to end minus duration
                        - if begin is not empty and end is empty and duration is > 0 (running records = 0): set end to begin plus duration
                    #}

                    function changedDuration(value)
                    {
                        var momentDuration = moment.duration(value);
                        if (!momentDuration.isValid()) {
                            return;
                        }
                        
                        var beginField = document.getElementById('{{ blockPrefix }}_begin');
                        var endField = document.getElementById('{{ blockPrefix }}_end');
                        var format = endField.dataset.format;
                        var begin = beginField.value;
                        var end = endField.value;
                        var duration = momentDuration.asSeconds();

                        if (begin === '' && end === '') {
                            applyDateToField(beginField, moment(), format);
                            applyDateToField(endField, moment(beginField.value, format).add(duration, 'seconds'), format); 
                        } else if (begin === '' && end !== '') {
                            applyDateToField(beginField, moment(end, format).subtract(duration, 'seconds'), format);
                        } else if (begin !== '' && duration > 0) {
                            applyDateToField(endField, moment(beginField.value, format).add(duration, 'seconds'), format); 
                        }
                    }
                    
                    function applyDateToField(field, momentObj, format)
                    {
                        field.value = momentObj.format(format);
                        if (jQuery(field).data('daterangepicker') !== undefined) {
                            jQuery(field).data('daterangepicker').setStartDate(momentObj);
                            jQuery(field).data('daterangepicker').setEndDate(momentObj);
                        }
                    }
                </script>
            {% endif %}
        {% endblock %}
    {% endembed %}
{% endblock %}
