{% block search_map %}

  {% include 'rgd/_include/viewer.html' %}

  <script>
    // script to add search parameters to the map
    let searchParams = JSON.parse('{{ search_params|escapejs }}');
    if (!_.isEmpty(searchParams) && !_.isEmpty(searchParams.q)) {
      let searchGeometry = JSON.parse(searchParams.q)
      // Add search parameters as markers
      if (searchGeometry.type == 'Point') {
        // center map here by default (in case no data appears in search)
        map.center({
           x: searchGeometry.coordinates[0],
           y: searchGeometry.coordinates[1]
         })
        var data = [{
          lon: searchGeometry.coordinates[0],
          lat: searchGeometry.coordinates[1]
        }, ]
        var searchMarker = layer.createFeature('marker')
          .data(data)
          .position(function(marker) {
            return {
              x: marker.lon,
              y: marker.lat
            };
          })
          .draw();

        function drawCircle(distance, color='black') {
          var radius = Number(distance) / 1.11 * 0.00001
          var theta = _.range(0, 2*Math.PI+Math.PI/32, Math.PI/32)
          var lineNodes = theta.map(e => {
            var x = radius * Math.cos(e) + Number(searchGeometry.coordinates[0])
            var y = radius * Math.sin(e) + Number(searchGeometry.coordinates[1])
            return {x: x, y: y}
          })
          var lineData = []
          for (i = 0; i < lineNodes.length - 1; i++) {
            lineData.push([lineNodes[i], lineNodes[i+1]])
          }
          var line = layer.createFeature('line')
            // set the data to our example data
            .data(lineData)
            // add some styles
            .style({
              // use a function for determining if the line should be closed based
              // on where it is in our list of data.
              closed: function (item, itemIndex) {
                return itemIndex === 1 || itemIndex === 3 || itemIndex === 5;
              },
              strokeColor: color,
              strokeWidth: 2
            });
          // draw the feature
          line.draw();
        }


        if (searchParams.distance_min != undefined) {
          drawCircle(searchParams.distance_min, 'blue')
        }
        if (searchParams.distance_max != undefined) {
          drawCircle(searchParams.distance_max, 'red')
        }
      } else {
        // Do GeoJSON display
        let searchreader = geo.createFileReader('geojsonReader', {
          'layer': layer
        });

        searchreader.read(searchGeometry, (features) => {
          features[0].style({
            fillOpacity: 0.0,
            strokeColor: 'red'
          })
          .draw();
        });
      }
    }
  </script>

{% endblock %}
