{% extends "tileserver/base.html" %}

{% block content %}

<script>
  var tileUrl = `${host}/api/tiles/{z}/{x}/{y}.png?projection=EPSG:3857&filename=${filename}`;

  function insertWindowUrlParam(key, value) {
    if (history.pushState) {
      let searchParams = new URLSearchParams(window.location.search);
      if (value === undefined || value === "") {
        searchParams.delete(key);
      } else {
        searchParams.set(key, value);
      }
      let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
      window.history.pushState({
        path: newurl
      }, '', newurl);
    }
  }

  function updateTileUrlOption(option, value) {
    const url = new URL(tileUrl);
    const urlParams = new URLSearchParams(window.location.search);
    var searchParams = url.searchParams;
    if (value === undefined || value === "") {
      searchParams.delete(option);
    } else {
      searchParams.set(option, value);
    }
    const tileFormatEncoded = '/%7Bz%7D/%7Bx%7D/%7By%7D.';
    const tileFormat = '/{z}/{x}/{y}.';
    tileUrl = url.toString().replace(tileFormatEncoded, tileFormat);
    insertWindowUrlParam(option, value);
  }

  const windowSearch = new URLSearchParams(window.location.search);
  const windowSearchParams = Object.fromEntries(windowSearch.entries());
  for (const [option, value] of Object.entries(windowSearchParams)) {
    updateTileUrlOption(option, value);
  }

  // MUST implement updateTileLayer()
</script>

{% block tileViewer %}
{% endblock %}

{% endblock %}
