{% extends "_base.html" %}
{% block title %}{{ super() }} {{ data['title'] }} {% endblock %}
{% block crumbs %}{{ super() }}
/ <a href="{{ data['collections_path'] }}">{% trans %}Collections{% endtrans %}</a>
{% for link in data['links'] %}
  {% if link.rel == 'collection' %} /
    <a href="{{ data['dataset_path'] }}">{{ link['title'] | string | truncate( 25 ) }}</a>
    {% set col_title = link['title'] %}
  {% endif %}
{% endfor %}
/ <a href="{{ data['items_path']}}">{% trans %}Items{% endtrans %}</a>
{% endblock %}
{% block extrahead %}
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css"/>
    <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster/dist/MarkerCluster.css"/>
    <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster/dist/MarkerCluster.Default.css"/>
    <script src="https://unpkg.com/leaflet.markercluster/dist/leaflet.markercluster-src.js"></script>

    {% if data['itemtype'] == 'record' %}
    <link rel="stylesheet" href="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.css"/>
    <script src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
    {% endif %}
{% endblock %}

{% block body %}
  <section id="items"></section>
  <section id="collection">
    <h1>{% for l in data['links'] if l.rel == 'collection' %} {{ l['title'] }} {% endfor %}</h1>
  </section>
  <section id="items">
    {% if data['features'] %}
    {% if data['itemtype'] == 'record' %}
    <div class="row">
      <div class="col-sm-12 col-md-6">
        <form id="searchForm">
          <div class="row">
            <div class="col-sm-4">
              <label for="q">Search</label>
              <input name="q" id="q" type="text" class="form-control search-input" placeholder="Search">
            </div>
            <div class="col-sm-4">
              <label for="datetime_begin">Start date</label>
              <input name="datetime_begin" id="datetime_begin" type="date" class="form-control" />
            </div>
            <div class="col-sm-4">
              <label for="datetime_end">End date</label>
              <input name="datetime_end" id="datetime_end" type="date" class="form-control" />
            </div>
          </div>
          <div class="row">
            <div class="col-sm-12">
              <input class="form-check-input" onchange="checkSpatialFilter()"  type="checkbox" id="spatial_filter_check">
              <label class="form-check-label" for="spatial_filter_check">Spatial filter</label>
              <button type="submit" class="btn btn-primary" onclick="submitForm();">Search</button>
              <button type="reset" class="btn btn-secondary" onclick="document.getElementById('searchForm').reset();">Reset</button>
            </div>
          </div>
        </form>
      </div>
    </div>
    {% endif %}
    <div class="row">
      <div class="col-sm-12 col-md-6">
        <div class="row">
          <div class="col-sm-12">
            <div id="items-map"></div>
          </div>
          <div class="col-sm-12">
            <div class="row">
                <div class="col-sm-12">
                    {% if data['numberMatched'] %}
                    <p>{% trans %}Items in this collection{% endtrans %}: {{ data['numberMatched'] }}</p>
                    {% endif %}
                </div>
            </div>
            <div class="row">
                <div class="col-sm-12">
                  {% trans %}Limit{% endtrans %}:
                  <select id="limits">
                    <option value="{{ config['server']['limits']['default_items'] }}">{{ config['server']['limits']['default_items'] }} ({% trans %}default{% endtrans %})</option>
                    <option value="100">100</option>
                    <option value="1000">1,000</option>
                    <option value="2000">2,000</option>
                  </select>
                  <p>{% trans %}Warning: Higher limits not recommended!{% endtrans %}</p>
                  <script>
                    var select = document.getElementById('limits');
                    var defaultValue = select.getElementsByTagName('option')[0].value;
                    let params = (new URL(document.location)).searchParams;
                    select.value = params.get('limit') || defaultValue;
                    select.addEventListener('change', ev => {
                      var limit = ev.target.value;
                      document.location.search = `limit=${limit}`;
                    });
                  </script>
                </div>
            </div>
            <div class="row">
              <div class="col-sm-12">
                {% for link in data['links'] %}
                {% if link['rel'] == 'prev' and data['offset'] > 0 %}
                <a role="button" href="{{ link['href'] }}">{% trans %}Prev{% endtrans %}</a>
                {% elif link['rel'] == 'next' and data['features'] %}
                <a role="button" href="{{ link['href'] }}">{% trans %}Next{% endtrans %}</a>
                {% endif %}
                {% endfor %}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="col-sm-12 col-md-6" style="overflow-x: scroll;">
        {% set props = [] %}
        <table class="table table-striped table-bordered">
          <thead>
            <tr>
              {% if data.get('uri_field') %}
                {% set uri_field = data.uri_field %}
                <th>{{ uri_field }}</th>
              {% elif data.get('title_field') %}
                {% set title_field = data.title_field %}
                <th>{{ title_field }}</th>
              {% else %}
                <th>id</th>
              {% endif %}

              {% for k in data['features'][0]['properties'].keys() %}
                {% if k not in [data.id_field, data.title_field, data.uri_field, 'extent'] %}
                  {% set props = props.append(k) %}
                  <th>{{ k | striptags }}</th>
                {% endif %}
              {% endfor %}
            </tr>
          </thead>
          <tbody>
            {% for ft in data.features %}
              <tr>
                {% if data.get('uri_field') %}
                  {% set uri_field = data.uri_field %}
                  <td data-label="{{ uri_field }}">
                    <a href="{{ ft.properties.get(uri_field) }}" title="{{ ft.properties.get(uri_field) }}">
                      {{ ft.properties.get(uri_field) }}
                    </a>
                  </td>
                {% elif data.get('title_field') %}
                  {% set title_field = data.title_field %}
                  <td data-label="{{ title_field }}">
                    <a href="{{ data.items_path }}/{{ ft['id'] }}" title="{{ ft.properties.get(title_field) }}">
                      {{ ft.properties.get(title_field) | string | truncate( 35 ) }}
                    </a>
                  </td>
                {% else %}
                  <td data-label="id">
                    <a href="{{ data.items_path }}/{{ ft.id }}" title="{{ ft.id }}">
                      {{ ft.id | string | truncate( 12 )  }}
                    </a>
                  </td>
                {% endif %}

                {% for prop in props %}
                  <td data-label="{{ prop }}">
                    {{ ft.properties.get(prop, '') | string | truncate( 35 ) }}
                  </td>
                {% endfor %}

              </tr>
            {% endfor %}
          </tbody>
          </table>
      </div>
    </div>
    {% elif data['numberMatched'] %}
    <div class="row">
      <div class="col-sm-12">
        <p>{% trans %}Items in this collection{% endtrans %}: {{ data['numberMatched'] }}</p>
      </div>
    </div>
    {% else %}
    <div class="row col-sm-12">
        <p>{% trans %}No items{% endtrans %}</p>
    </div>
    {% endif %}
    </section>
{% endblock %}

{% block extrafoot %}
{% if data['features'] %}
    <script>
    {% if data['itemtype'] == 'record' %}

    document.getElementById("q").addEventListener("keydown", function(event) {
        if (event.key === "Enter") {
            event.preventDefault();
            submitForm();
        }
    });

    function submitForm() {
        var query_string = [];
        var datetime = [];

        var q = document.getElementById('q').value;
        var datetime_begin = document.getElementById('datetime_begin').value;
        var datetime_end = document.getElementById('datetime_end').value;

        if (q) {
            query_string.push('q=' + encodeURIComponent(q));
        }
        if (datetime_begin !== "") {
            datetime.push(datetime_begin + 'T00:00:00Z');
        } else {
            datetime.push('..');
        }
        if (datetime_end !== "") {
            datetime.push(datetime_end + 'T23:59:59Z');
        } else {
            datetime.push('..');
        }

        datetime = datetime.join('/');

        if (datetime !== '../..') {
            query_string.push('datetime=' + encodeURIComponent(datetime));
        }

        if (map.hasLayer(rectangle)) {
            query_string.push('bbox=' + getBbox(rectangle).join(','));
        }

        if (query_string.length > 0)  {
            document.location.href = '{{ data['items_path'] }}' + '?' + query_string.join('&');
        }
    }
    {% endif %}
    var map = L.map('items-map').setView([{{ 45 }}, {{ -75 }}], 5);
    map.addLayer(new L.TileLayer(
        '{{ config['server']['map']['url'] }}', {
            maxZoom: 18,
            attribution: '{{ config['server']['map']['attribution'] | safe }}'
        }
    ));
    var geojson_data = {{ data['features'] | to_json | safe }};

    var items = new L.GeoJSON(geojson_data, {
        onEachFeature: function (feature, layer) {
            var url = '{{ data['items_path'] }}/' + feature.id + '?f=html';
            var html = '<span><a href="' + url + '">' + {% if data['title_field'] %} feature['properties']['{{ data['title_field'] }}'] {% else %} feature.id {% endif %} + '</a></span>';
            layer.bindPopup(html);
        }
    });
    var markers = L.markerClusterGroup({
        disableClusteringAtZoom: 9,
        chunkedLoading: true,
        chunkInterval: 500,
    });
    markers.clearLayers().addLayer(items);
    map.addLayer(markers);

    map.fitBounds(items.getBounds());

    {% if data['itemtype'] == 'record' %}
    function getBbox(rect) {
        bounds = rect.getBounds();

        return [bounds.getWest(),
                bounds.getSouth(),
                bounds.getEast(),
                bounds.getNorth()];
    }

    var rectangle;
    function setRectangle(bbox) {
        if (rectangle) {
            rectangle.setBounds(bbox)
        } else {
            rectangle = L.rectangle(bbox);
            rectangle.editing.enable();
            rectangle.setStyle({color :'green'});
        }
        map.addLayer(rectangle);
    }

    function checkSpatialFilter() {
        if (map.hasLayer(rectangle)) {
            rectangle.remove();
        } else {
            setRectangle(map.getBounds().pad(-0.95));
        }
    }

    var form = document.getElementById("searchForm");
    form.addEventListener("submit", submitForm);
    {% endif %}
    </script>
{% endif %}
{% endblock %}
