<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{{name}} - TileServer GL</title>
  <link rel="stylesheet" type="text/css" href="{{public_url}}maplibre-gl.css{{&key_query}}" />
  <link rel="stylesheet" type="text/css" href="{{public_url}}maplibre-gl-inspect.css{{&key_query}}" />
  <link rel="stylesheet" type="text/css" href="{{public_url}}leaflet.css{{&key_query}}" />
  <script src="{{public_url}}maplibre-gl.js{{&key_query}}"></script>
  <script src="{{public_url}}maplibre-gl-inspect.js{{&key_query}}"></script>
  <script src="{{public_url}}leaflet.js{{&key_query}}"></script>
  <script src="{{public_url}}leaflet-hash.js{{&key_query}}"></script>
  <style>
    body { margin:0; padding:0; }
    #map { position:absolute; top:0; bottom:0; width:100%; }
    .leaflet-control-layers-toggle {
      background-image: url({{public_url}}images/layers.png{{&key_query}});
      width: 36px;
      height: 36px;
    }
    .leaflet-retina .leaflet-control-layers-toggle {
      background-image: url({{public_url}}images/layers-2x.png{{&key_query}});
      background-size: 26px 26px;
    }
    .leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */
      background-image: url({{public_url}}images/marker-icon.png{{&key_query}});
    }
  </style>
</head>
<body>
  <h1 style="display:none;">{{name}}</h1>
  <div id='map'></div>
  <script>
    function isWebglSupported() {
        if (window.WebGLRenderingContext) {
            const canvas = document.createElement('canvas');
            try {
                const context = canvas.getContext('webgl2') || canvas.getContext('webgl');
                if (context && typeof context.getParameter == 'function') {
                    return true;
                }
            } catch (e) {
                // WebGL is supported, but disabled
            }
            return false;
        }
        // WebGL not supported
        return false;
    }
    var q = (location.search || '').substr(1).split('&');
    var preference =
      q.indexOf('vector') >= 0 ? 'vector' :
        (q.indexOf('raster') >= 0 ? 'raster' :
          (isWebglSupported() ? 'vector' : 'raster'));

    var keyMatch = location.search.match(/[\?\&]key=([^&]+)/i);
    var keyParam = keyMatch ? '?key=' + keyMatch[1] : '';    

    if (preference == 'vector') {
      maplibregl.setRTLTextPlugin('{{public_url}}mapbox-gl-rtl-text.js' + keyParam);
      var map = new maplibregl.Map({
        container: 'map',
        style: '{{public_url}}styles/{{id}}/style.json' + keyParam,
        hash: true,
        maxPitch: 85
      });
      map.addControl(new maplibregl.NavigationControl({
         visualizePitch: true,
         showZoom: true,
         showCompass: true
      }));
      map.addControl(new MaplibreInspect({
         showMapPopupOnHover: false,
         showInspectMapPopupOnHover: false,
         selectThreshold: 5
      }));
    } else {
        var map = L.map('map', { minZoom: 1, zoomControl: false });
        new L.Control.Zoom({ position: 'topright' }).addTo(map);
        
        var tile_urls = [], tile_attribution, tile_minzoom, tile_maxzoom;
        var url = '{{public_url}}styles/512/{{id}}.json' + keyParam;
        var req = new XMLHttpRequest();
        req.overrideMimeType("application/json");
        req.open('GET', url, true);
        req.onload = function() {
            var jsonResponse = JSON.parse(req.responseText);
            for (key in jsonResponse) {
              var keyl = key.toLowerCase();
                switch(keyl) {
                  case "tiles":
                    tile_urls = jsonResponse[key];
                    break;
                  case "attribution":
                    tile_attribution = jsonResponse[key];
                    break;
                  case "minzoom":
                    tile_minzoom = jsonResponse[key];
                    break;
                  case "maxzoom":
                    tile_maxzoom = jsonResponse[key];
                    break;
                }
            }

            for (tile_url in tile_urls) {
                L.tileLayer(tile_urls[tile_url], {
                    tileSize: 512,
                    zoomOffset: -1,
                    minZoom: tile_minzoom,
                    maxZoom: tile_maxzoom,
                    attribution: tile_attribution
                }).addTo(map);
            }
        
            map.eachLayer(function(layer) {
              // do not add scale prefix even if retina display is detected
              layer.scalePrefix = '.';
            });
        };
        req.send(null);
      
        setTimeout(function() {
            new L.Hash(map);
        }, 0);
    }
  </script>
</body>
</html>
