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

{% block scripts %}
{{super()}}
  <script src="{{ url_for('static', filename='js/ol.js') }}"></script>
  <script type="text/javascript">
    // global object for storing bboxes in different crs per layer
    var boundingboxes = {};
    var capabilities = '';

    if ($('#url').val() != '') {
      const url = $('#url').val();
      $('#input-url').val(url);
      getCapabilities(url).then(() => {
        var wmsLayer = capabilities.Capability.Layer.Layer;
        wmsLayer.map(layer => {addLayerRow(layer)});
  
        // select srs
        getSRS(wmsLayer.find(layer => layer.Name === $('#name').val()).BoundingBox);
        // select format
        getFormats(capabilities.Capability.Request.GetMap.Format);
      });
    }

    function getCapabilities(url) {
      $('#url').val(url);
      // add protocol and host
      if(url.match("^\/")) {
        url = location.protocol + "//" + location.host + url;
      // add protocol
      } else if(!url.match("^http")) {
        url = location.protocol + "//" + url;
        $('#url').val(url);
      }

      // add cabilities url paramter 
      if(url.indexOf('?') > 0) {
        var base = url.substring(0, url.indexOf('?'));
        url = base + '?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetCapabilities';
      } else {
        url += '?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetCapabilities';
      }

      // read capbilities from input-url
      return new Promise((success, failure) => {
        $.get(url)
          .then(function(data) {
            $("#wms-table").css('display', '');
            var parser = new ol.format.WMSCapabilities();
            capabilities = parser.read(data);
            success();
          },function() {
            $("#wms-table").css('display', 'none');
            alert('Could not read capabilities!');
          })
      })
    }

    function getBoundingBoxes(name, bboxes) {
      // add boundingboxes
      var item = {};
      item[name] = bboxes;
      $.extend(boundingboxes, item);
    }

    function getFormats(formats) {
      $.each(formats, function(key, format) {
        $('#select-format').append('<option value=' + format + '>' + format + '</option>');
        if ($('#format').val() != '') {
          $('#select-format').find('option').each(function() {
            if ($(this).val() === $('#format').val()) {
              $(this).attr('selected', true);
            }
          })
        }
      });
      $('#select-format').change();
    }

    function getSRS(bboxes) {
      $('#select-srs').find('option').remove();
      $.each(bboxes, function(key, bbox) {
        $('#select-srs').append('<option value=' + bbox.crs + '>' + bbox.crs + '</option>');
      });
      if ($('#srs').val() != '') {
        $('#select-srs').find('option').each(function() {
          if ($(this).val() === $('#srs').val()) {
            $(this).attr('selected', true);
            // $('#select-srs').change();
          }
        })
      }
    }

    function addLayerRow(layer) {
      if(Array.isArray(layer)) {
        for(i in layer) {
          addLayerRow(layer[i]);
        }
      } else {
        if(layer.Name) {
          getBoundingBoxes(layer.Name, layer.BoundingBox);

          // add rows
          let row_class = "layer-row";
          if ($('#name').val() != '') {
            if (layer.Name === $('#name').val()) {
              row_class = "layer-row selected";
            }
          }
          var row = '<tr class="' + row_class + '">';
          row += '<td class="wms-title">' + layer.Title + '</td>';
          row += '<td class="wms-name">' + layer.Name + '</td>';
          // add hidden td
          if (layer.Attribution) { 
            row += '<td class="wms-attribution hidden">' + layer.Attribution.Title + '</td>'; 
          }
          row += '</tr>';
          $('#wms-table > tbody:last-child').append(row);
        }
        if(layer.Layer) {
          addLayerRow(layer.Layer);
        }
      }
    }

    // read capabilities from url and fill form
    $('#btn-connect').click(function() {
 
      // clear form
      $('#url').val('');
      $('#select-srs').find('option').remove();
      $('#select-format').find('option').remove();
      $('#form').trigger('reset');
      $('#wms-table>tbody').empty();
      boundingboxes = {};

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

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

      getCapabilities(url).then(() => {
        var wmsLayer = capabilities.Capability.Layer.Layer;
        wmsLayer.map(layer => {addLayerRow(layer)});
  
        // select srs
        if ($('#name').val() != '') {
          getSRS(wmsLayer.find(layer => layer.Name === $('#name').val()).BoundingBox);
        } else {
          getSRS(capabilities.Capability.Layer.BoundingBox);
        }
        // select format
        getFormats(capabilities.Capability.Request.GetMap.Format);
      });
    });

    // highlight selected row and set hidden vars
    $('#wms-table').on('click', '.layer-row', function(event) {
      // highlight selected row
      $(this).addClass('selected').siblings().removeClass('selected');
      // set hidden vars
      const name = $(this).find('td.wms-name').text().trim();
      boundingboxes = {};
      const bboxes = capabilities.Capability.Layer.Layer.find(layer => layer.Name === name).BoundingBox;
      getBoundingBoxes(name, bboxes);
      getSRS(bboxes);
      const srs = $('#select-srs option:selected').text().trim();
      const bbox = boundingboxes[name].find(box => box.crs === srs).extent;
      $('#name').val(name);
      $('#title').val($(this).find('td.wms-title').text());
      $('#srs').val(srs);
      $('#bbox').val(bbox);
      if($(this).find('td.wms-attribution').text() !== "undefined") {
        $('#attribution').val($(this).find('td.wms-attribution').text().trim());
      }
    });

    // srs change
    $('#select-srs').change(function() {
      const srs = $(this).find('option:selected').text().trim();
      const name = $('#name').val();
      boundingboxes = {};
      const bboxes = capabilities.Capability.Layer.Layer.find(layer => layer.Name === name).BoundingBox;
      getBoundingBoxes(name, bboxes);
      const bbox = boundingboxes[name].find(box => box.crs === srs).extent;
      $('#srs').val(srs); 
      $('#bbox').val(bbox);
    });
    // format change
    $('#select-format').change(function() {
      $('#format').val($(this).find('option:selected').text().trim()); 
    });
  </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.wmslayer.add') }}{% endblock %}
{% block container %}
  <h1>{{ i18n('plugins.themes.wmslayer.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.wmslayer.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 ellipsis" id="wms-table" style="display: none">
        <thead>
          <tr>
            <th>{{ i18n('interface.common.title') }}</th>
            <th>{{ i18n('plugins.themes.common.layer') }}</th>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
    </div>
    <form id="form" class="form form-horizontal" action="{{ action }}" method="post" style="padding: 2.5em 0;">
      {{ form.csrf_token }}
      {{ wtf.render_field(form.title, form_type="horizontal", horizontal_columns=('sm', 2, 10)) }}
      <div class="mb-3 row">
        <label class="col-form-label col-sm-2" for="select-crs">{{ i18n('plugins.themes.common.crs') }}</label>
        <div class="col-sm-10">
          <select class="form-control" id="select-srs"></select>
        </div>
      </div>
      <div class="mb-3 row">
        <label class="col-form-label col-sm-2" for="select-format">{{ i18n('plugins.themes.common.format') }}</label>
        <div class="col-sm-10">
          <select class="form-control" id="select-format"></select>
        </div>
      </div>
      {{ 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)) }}
      {{ wtf.render_field(form.tiled, form_type="horizontal", horizontal_columns=('sm', 2, 10)) }}
      {{ form.url }}
      {{ form.name }}
      {{ form.format }}
      {{ form.srs }}
      {{ form.bbox }}
      {{ 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 %}
