{% extends "layout.html" %}
{% from "_macros.html" import render_form_styles, render_form_scripts, render_jquery_steps_header, render_google_filter_autocomplete_header, render_event_dates_filter_form, render_pagination, render_place, render_events_sub_menu %}

{%- block title -%}
{{ _('Event Dates') }}
{%- endblock -%}

{% block styles %}
{{ render_form_styles() }}
<link rel="stylesheet" href="{{ url_for('static', filename='ext/leaflet.1.5.1.css')}}" />
<link rel="stylesheet" href="{{ url_for('static', filename='ext/MarkerCluster@1.4.1.Default.css')}}" />
<link rel="stylesheet" href="{{ url_for('static', filename='ext/MarkerCluster.1.4.1.css')}}" />
<link rel="stylesheet" href="{{ url_for('static', filename='ext/L.Control.Locate.0.68.0.min.css')}}" />
{% endblock %}

{% block header_before_site_js %}
{{ render_form_scripts() }}
<script src="{{ url_for('static', filename='ext/leaflet.1.5.1.js')}}"></script>
<script src="{{ url_for('static', filename='ext/leaflet.markercluster.1.4.1.js')}}"></script>
<script src="{{ url_for('static', filename='ext/L.Control.Locate.0.68.0.min.js')}}" charset="utf-8"></script>
{%- endblock -%}

{% block header %}
<script src="{{ url_for('static', filename='svg-icon.js')}}"></script>
{{ render_jquery_steps_header() }}
{{ render_google_filter_autocomplete_header() }}
<script>

    var page = 1;
    var per_page = 18; // 3*6

    var leaflet_map = null;
    var map_cluster_group = null;
    var event_dates = null;
    var current_data = null;
    var arrayOfMarkers = [];

    function init_leaflet_map() {
        if (leaflet_map != null) {
            return;
        }

        leaflet_map  = L.map('map').fitWorld();

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(leaflet_map);

        L.control.locate({
            keepCurrentZoomLevel: true,
            icon: 'fa fa-location-arrow'
        }).addTo(leaflet_map);
    }

    function clear_events_from_map() {
        if (leaflet_map == null) {
            return;
        }

        if (map_cluster_group != null) {
            map_cluster_group.clearLayers();
        }

        arrayOfMarkers = [];
    }

    function show_event_in_list(event_id) {
        var card = $('#event_card_' + event_id);
        scroll_to_element(
            card,
            function () {
                card.effect("highlight", {}, 500);
            });
    }

    function fly_to_event(latitude, longitude) {
        $('#map').show();

        if (arrayOfMarkers.length == 0) {
            add_events_to_map();
        }

        scroll_to_element(
            $('#map'),
            function () {
                leaflet_map.flyTo([latitude, longitude], 16);
            });
    }

    function format_event_date_instance(instance, allday) {
        if (allday) {
            return instance.format("dd. DD.MM.YYYY");
        }

        return instance.format("dd. DD.MM.YYYY LT")
    }

    function add_events_to_map() {
        init_leaflet_map();
        clear_events_from_map();

        $.each(event_dates, function(index, event_date) {
            event = event_date.event;
            if (event.place != null && event.place.location != null && event.place.location.latitude != null) {
                var location = event.place.location;
                var start = moment(event_date.start);
                var title = format_event_date_instance(start, event_date.allday) + ' ' + '<a href="#" onclick="show_event_in_list(\'' + event_date.id + '\'); return false;">' + event.name + '</a>';

                var icon = new L.DivIcon.SVGIcon({
                    color: "#000",
                    fillColor: 'blue',
                    fillOpacity: 1.0,
                    iconSize: [28,41],
                    circleRatio: 0.35
                });

                var marker = L.marker([location.latitude, location.longitude], { icon: icon }).bindPopup(title);
                arrayOfMarkers.push(marker);
            }
        });

        if (arrayOfMarkers.length == 0) {
            return;
        }

        var group_was_created = false;

        if (map_cluster_group == null) {
            map_cluster_group = L.markerClusterGroup({ disableClusteringAtZoom: 16});
            group_was_created = true;
        }

        map_cluster_group.addLayers(arrayOfMarkers);

        if (group_was_created) {
            leaflet_map.addLayer(map_cluster_group);
        }

        leaflet_map.fitBounds(map_cluster_group.getBounds());
    }

    function toggle_map() {
        if ($('#map').is(":visible")) {
            $('#map').hide();
        } else {
            $('#map').show();
            add_events_to_map();
        }
    }

    function start_request() {
        handle_request_start();

        var result_list = $("#result_list");
        result_list.empty();

        var req_data = $("#filter_form :input").filter(function () {
            return this.value.length > 0
        }).serialize()
        req_data += '&page=' + page + '&per_page=' + per_page;

        $.ajax({
            url: "{{ url_for('api_v1_event_date_search') }}",
            type: "get",
            dataType: "json",
            data: req_data,
            error: function(xhr, status, error) {
                handle_request_error(xhr, status, error);
            },
            success: function (data) {

                var content = '';
                current_data = data;
                event_dates = data.items;
                var event_date_count = event_dates.length;
                var cols = 3;

                $.each(event_dates, function(index, event_date) {
                    event = event_date.event;
                    var is_card_deck = (index % cols == 0);

                    if (is_card_deck) {
                        if (content != '') {
                            content += '</div>';
                        }
                        content += '<div class="card-deck">';
                    }

                    var start = moment(event_date.start);
                    var img_tag = '';

                    if (event.photo != null) {
                        img_tag = '<img src="' + event.photo.image_url + '" class="card-img-top" style="object-fit: cover; height: 12vh;" alt="Event image" />';
                    } else {
                        img_tag = '<div class="bg-light d-flex align-items-center justify-content-center" style="height: 12vh;"><i class="fa-calendar far h1 text-muted"></i></div>';
                    }

                    var map_link_start = '';
                    var map_link_end = '';

                    if (event.place != null && event.place.location != null && event.place.location.latitude != null) {
                        var location = event.place.location;
                        map_link_start = '<a href="#" onclick="fly_to_event(' + location.latitude + ', ' + location.longitude + '); return false;">';
                        map_link_end = '</a>';
                    }

                    content += '<div class="card mb-3" id="event_card_' + event_date.id + '">' +
                                        img_tag +
                                        '<div class="card-body" style="padding:0.5rem">' +
                                            '<div class="small text-uppercase" style="font-weight: 600;">' + format_event_date_instance(start, event_date.allday) + '</div>' +
                                            '<h2 class="card-title m-0"><a href="eventdate/' + event_date.id + '" class="stretched-link text-body">' + event.name + '</a> <span class="small" style="vertical-align: middle;">' + render_event_warning_pills(event) + '</span></h2>' +
                                            '<div class="text-muted" style="font-weight: 500;">' + map_link_start + event.place.name + map_link_end + '</div>' +
                                        '</div>' +
                                '</div>';
                });

                if (content != '') {
                    var remaining_cols = (cols - (event_date_count % cols)) % cols;

                    for (i = 0; i < remaining_cols; i++) {
                        content += '<div class="card mb-3"></div>';
                    }

                    content += '</div>';
                }

                result_list.append(content);

                if (data.has_prev) {
                    $('#first_item,#prev_item').removeClass('disabled');
                } else {
                    $('#first_item,#prev_item').addClass('disabled');
                }

                if (data.has_next) {
                    $('#last_item,#next_item').removeClass('disabled');
                } else {
                    $('#last_item,#next_item').addClass('disabled');
                }

                if (data.has_prev || data.has_next) {
                    $('#page_info_text').text("Seite " + data.page + " von " + data.pages + " (" + data.total + " insgesamt)")
                    $('#page_info').removeClass("d-none");
                } else {
                    $('#page_info').addClass("d-none");
                }

                handle_request_success();

                if (leaflet_map != null) {
                    add_events_to_map();
                }
            }
        });
    }

    $( function() {
        $("#filter_form").submit(function(e) {
            e.stopPropagation();
            page = 1;
            start_request();
            return false;
        });

        $("#first_link").click(function(){
            page = 1;
            start_request();
            return false;
        });

        $("#prev_link").click(function(){
            if (page > 1) {
                page--;
                start_request();
            }
            return false;
        });

        $("#next_link").click(function(){
            page++;
            start_request();
            return false;
        });

        $("#last_link").click(function(){
            page = current_data.pages;
            start_request();
            return false;
        });

        $('#map').hide();
        $("#filter_form").submit();
    });
    </script>
{% endblock %}

{% block content %}

    <h1 class="mb-3">{{ _('Event Dates') }}</h1>
    <div class="btn-group mb-3">
        <button type="button" id="toggle-search-btn" class="btn btn-outline-secondary btn-sm" data-toggle="collapse" data-target="#search_form" aria-expanded="{% if form.is_submitted() %}true{% else %}false{% endif %}"><i class="fa fa-search"></i> {{ _('Search') }}</button>
        <button type="button" id="toggle-map-btn" class="btn btn-outline-secondary btn-sm" onclick="toggle_map()"><i class="fa fa-map"></i> {{ _('Map view') }}</button>
    </div>

    <div class="{% if form.is_submitted() %}{% else %}collapse{% endif %}" id="search_form">
        {{ render_event_dates_filter_form(form) }}
    </div>

    <div class="row">
        <div class="col-md mx-3 mb-3" id="map" style="height: 400px;">
        </div>
        <div class="col-md">
            <div id="result_container">
                <div class="m-1 small text-center text-secondary" id="result_info"></div>
                <div style="min-height: 300px;">
                    <div id="result_list">
                    </div>
                </div>
                <nav aria-label="Page navigation">
                    <ul class="pagination">
                          <li class="page-item disabled" id="first_item"><a class="page-link" id="first_link" href="#" title="{{ _('First') }}"><i class="fa fa-angle-double-left"></i></a></li>
                          <li class="page-item disabled" id="prev_item"><a class="page-link" id="prev_link" href="#" title="{{ _('Previous') }}"><i class="fa fa-angle-left"></i></a></li>
                          <li class="page-item disabled d-none" id="page_info"><span class="page-link" id="page_info_text"></span></li>
                          <li class="page-item disabled" id="next_item"><a class="page-link" id="next_link" href="#" title="{{ _('Next') }}"><i class="fa fa-angle-right"></i></a></li>
                          <li class="page-item disabled" id="last_item"><a class="page-link" id="last_link" href="#" title="{{ _('Last') }}"><i class="fa fa-angle-double-right"></i></a></li>
                    </ul>
                </nav>
            </div>
            <div class="spinner-border m-3" role="status" id="spinner" style="display: none;">
                <span class="sr-only">Loading&hellip;</span>
            </div>
            <div class="alert alert-danger m-3" role="alert" id="error_alert" style="display: none;"></div>
        </div>
    </div>

{% endblock %}