{% import "bootstrap5/form.html" as wtf %}
{% extends "templates/base.html" %}

{% block scripts %}
{{super()}}
  <script src="{{ url_for('static', filename='js/ol.js') }}"></script>
  <script src="{{ url_for('static', filename='js/proj4-src.min.js') }}"></script>
  <script type="text/javascript">
    // TODO: add more proj4 defs
    proj4.defs("EPSG:25832","+proj=utm +zone=32 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
    proj4.defs("EPSG:3948","+proj=lcc +lat_1=47.25 +lat_2=48.75 +lat_0=48 +lon_0=3 +x_0=1700000 +y_0=7200000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs ");
    proj4.defs("EPSG:2154","+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
    ol.proj.proj4.register(proj4);

    // highlight selected row and set hidden vars
    $('#wmts-table').on('click', '.layer-row', function(event) {
      // highlight selected row
      $(this).addClass('selected').siblings().removeClass('selected');
      // set hidden vars
      $('#url').val($(this).find('td.wmts-url').text());
      $('#title').val($(this).find('td.wmts-title').text());
      $('#name').val($(this).find('td.wmts-name').text());
      $('#tileMatrixSet').val($(this).find('td.wmts-tilematrix').text());
      $('#style').val($(this).find('td.wmts-style').text());
      $('#format').val($(this).find('td.wmts-format').text());
      $('#projection').val($(this).find('td.wmts-crs').text());
      $('#originX').val($(this).find('td.wmts-originX').text());
      $('#originY').val($(this).find('td.wmts-originY').text());
      $('#tileSize').val($(this).find('td.wmts-tilesize').text());
      $('#resolutions').val($(this).find('td.wmts-resolutions').text());
      $('#requestEncoding').val($(this).find('td.wmts-requestEncoding').text());
    });

    // read capabilities from input-url
    $('#btn-connect').click(function() {

      // clear form and table
      $('#form').trigger('reset');
      $('#wmts-table > tbody').html("");
      $('#btn-gen-tile-cache').prop('disabled', true);
      $('#with_capabilities').prop('checked', false);

      var url = $('#input-url').val().trim();

      // skip empty url
      if(!url) {
        return false;
      }

      // add http
      if(!url.match('^http')) { 
        url = "http://" + url
      }

      $.get(url)
      .then(function(data) {
        $("#wmts-table").css('display', '');
        var parser = new ol.format.WMTSCapabilities();
        var capabilities = parser.read(data);
        $('#capabilities').val(JSON.stringify(capabilities));

        var wmtsLayer = capabilities.Contents.Layer;
        wmtsLayer.map(layer => {
          layer.TileMatrixSetLink.map(tms => {
            try {
              var options = ol.source.WMTS.optionsFromCapabilities(capabilities, {layer: layer.Identifier, matrixSet: tms.TileMatrixSet});
              var row = '<tr class="layer-row">';
              row += '<td class="wmts-title">' + layer.Title + '</td>';
              row += '<td class="wmts-tilematrix">' + options.matrixSet + '</td>';
              row += '<td class="wmts-format">' + options.format + '</td>';
              row += '<td class="wmts-style">'+ options.style + '</td>';
              row += '<td class="wmts-crs">' + options.projection.code_ + '</td>';
              // add hidden td
              row += '<td class="wmts-url hidden">' + options.urls[0] + '</td>';
              row += '<td class="wmts-name hidden">' + options.layer + '</td>';
              row += '<td class="wmts-originX hidden">' + options.tileGrid.origins_[0][0] + '</td>';
              row += '<td class="wmts-originY hidden">' + options.tileGrid.origins_[0][1] + '</td>';
              row += '<td class="wmts-tilesize hidden">' + [options.tileGrid.tileSizes_[0], options.tileGrid.tileSizes_[0]] + '</td>';
              row += '<td class="wmts-resolutions hidden">' + options.tileGrid.resolutions_ + '</td>';
              row += '<td class="wmts-requestEncoding hidden">' + options.requestEncoding + '</td>';
              row += '</tr>';
              $('#wmts-table > tbody:last-child').append(row);
            } catch(e) {
              /* pass */
            }
          });
        });
      },function() {
      $("#wmts-table").css('display', 'none');
        alert('Could not read capabilities!');
      })
    });

    $('#with_capabilities').click(function() {
      if($("#with_capabilities").is(':checked')) {
        // show button
        $('#btn-gen-tile-cache').prop('disabled', false);
      } else {
        // hide button
        $('#btn-gen-tile-cache').prop('disabled', true);
      }
    });
  </script>
{% endblock %}
{%- block styles %}
    {{ super() }}
    <link href="{{ url_for('plugin_static', plugin='themes', filename='application.css') }}" rel="stylesheet">
{%- endblock styles %}

{% block title %}{{ i18n('plugins.themes.wmtslayer.add') }}{% endblock %}
{% block container %}
  <h1>{{ i18n('plugins.themes.wmtslayer.add') }}</h1>
  <div class="col-sm-7">
    <div class="row" style="padding: 2.5em 0">
      <div class="btn-group">
        <input type="text" id="input-url" class="form-control" placeholder="{{ i18n('plugins.themes.wmtslayer.capabilities_url') }}">
        <button id="btn-connect" class="btn btn-secondary" type="button">{{ i18n('plugins.themes.common.connect') }}</button>
      </div>
    </div>
    <div class="table-wrapper">
      <table class="table" id="wmts-table" style="display: none">
        <thead>
          <tr>
            <th>{{ i18n('plugins.themes.common.layer') }}</th>
            <th>{{ i18n('plugins.themes.wmtslayer.tilematrix') }}</th>
            <th>{{ i18n('plugins.themes.common.format') }}</th>
            <th>{{ i18n('plugins.themes.wmtslayer.style') }}</th>
            <th>{{ i18n('plugins.themes.common.crs') }}</th>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
    </div>
    <form id="form" class="form form-horizontal" action="{{ url_for('create_backgroundlayer', type=type) }}" method="post" style="padding-top: 2.5em 0;">
      {{ form.csrf_token }}
      {{ form.capabilities }}
      {{ wtf.render_field(form.title, form_type="horizontal", horizontal_columns=('sm', 2, 10)) }}
      {{ wtf.render_field(form.attribution, form_type="horizontal", horizontal_columns=('sm', 2, 10)) }}
      {{ wtf.render_field(form.thumbnail, form_type="horizontal", horizontal_columns=('sm', 2, 10)) }}
      {{ form.url }}
      {{ form.name }}
      {{ form.style }}
      {{ form.format }}
      {{ form.tileMatrixSet }}
      {{ form.projection }}
      {{ form.originX }}
      {{ form.originY }}
      {{ form.resolutions }}
      {{ form.requestEncoding }}
      {{ form.tileSize }}
      {{ wtf.render_field(form.submit, class="btn btn-primary") }}
      <button class="col-sm-offset-2 btn btn-danger" onclick="history.back()">Cancel</button>
    </form>
  </div>
{% endblock %}
