<div class="modal fade" id="form_points_modal" tabindex="-1" role="dialog"
     aria-labelledby="exampleModalLabel"
     aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"><%= _("Point of interest") %></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <%= form_with(model: @points_interest, url: create_points_interest_path(@group), remote: true) do |form| %>
          <div class="field d-none">
            <div class="row">
              <div class="col-md-12 col-xs-12 col-sm-12 px-7">
                <%= _("Type:") %>
              </div>
            </div>
            <div class="row">
              <div class="col-md-12 col-xs-12 col-sm-12 px-7">
                <select id="type" disabled="true">
                  <option selected value="Circle"><%= _("Circle") %></option>
                </select>
              </div>
            </div>
          </div>

          <div style="width: 100%; height: 400px;" id="points-interest"></div>

          <div class="field">
            <div class="row">
              <div class="col-md-12 col-xs-12 col-sm-12 px-7">
                <%= form.label :name %>
              </div>
            </div>
            <div class="row">
              <div class="col-md-12 col-xs-12 col-sm-12 px-7">
                <%= form.text_field :name, id: "geofence_name" %>
              </div>
            </div>
          </div>
          <div class="field">
            <div class="row">
              <div class="col-md-12 col-xs-12 col-sm-12 px-7">
                <%= form.label :description %>
              </div>
            </div>
            <div class="row">
              <div class="col-md-12 col-xs-12 col-sm-12 px-7">
                <%= form.text_area :description, id: "geofence_description" %>
              </div>
            </div>
          </div>

          <div class="field d-none">
            <div class="row">
              <div class="col-md-2 col-xs-2 col-sm-2 px-7">
                <label for="geofence_color"><%= _("Color") %></label>
              </div>
              <div class="col-md-2 col-xs-2 col-sm-2 px-7">
                <label for="geofence_border_color"><%= _("Border Color") %></label>
              </div>
              <div class="col-md-2 col-xs-2 col-sm-2 px-7">
                <label for="geofence_stroke_width"><%= _("Stroke Width") %></label>
              </div>
              <div class="col-md-2 col-xs-2 col-sm-2 px-7">
                <label for="geofence_fill_opacity"><%= _("Fill Opacity") %></label>
              </div>
            </div>
            <div class="row">
              <div class="col-md-2 col-xs-2 col-sm-2 px-7">
                <input type="color" id="geofence_color" name="geofence_color">
              </div>
              <div class="col-md-2 col-xs-2 col-sm-2 px-7">
                <input type="color" id="geofence_border_color" name="geofence_border_color">
              </div>
              <div class="col-md-2 col-xs-2 col-sm-2 px-7">
                <select style="width: 90px;" name="geofence_stroke_width" id="geofence_stroke_width">
                  <% (1..9).each do |n| %>
                    <option value="<%= n %>"><%= n %></option>
                  <% end %>
                </select>
              </div>
              <div class="col-md-2 col-xs-2 col-sm-2 px-7">
                <select style="width: 90px;" name="geofence_fill_opacity" id="geofence_fill_opacity">
                  <% (1..9).each do |n| %>
                    <option value="<%= n*10 %>"><%= n*10 %>%</option>
                  <% end %>
                </select>
              </div>
            </div>
          </div>

          <div style="display:none;" class="field">
            <div class="row">
              <div class="col-md-12 col-xs-12 col-sm-12 px-7">
                <%= form.label :area %>
              </div>
            </div>
            <div class="row">
              <div class="col-md-12 col-xs-12 col-sm-12 px-7">
                <%= form.text_area :area, id: "geofence_area" %>
              </div>
            </div>
          </div>
          <div class="row form-errors">
            <div class="col-md-12 col-xs-12 col-sm-12 px-7">
              <ul></ul>
            </div>
          </div>
          <div class="modal-footer">
            <%= render "shared/loading" %>
            <button type="button" class="btn-filter btn btn-light btn-sm fuse-ripple-ready" data-dismiss="modal"><%= t("utils.cancel_button") %></button>
            <button type="submit" class="btn btn-sm btn-send"><%= t("utils.send_button") %></button>
          </div>
        <% end %>
      </div>
    </div>
  </div>
</div>

<link rel="stylesheet" media="screen" type="text/css" href="<%= asset_path("color-picker.min.css") %>" />
<script type="text/javascript" src="<%= asset_path("color-picker.min.js") %>"></script>

<script>

    var googleLayerRoadmap = new ol.layer.Tile({
        title: "Google Road Map",
        type: 'base',
        visible: false,
        source: new ol.source.TileImage({url: 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}'}),
    });

    var googleLayerHybrid = new ol.layer.Tile({
        title: "Google Satellite & Roads",
        type: 'base',
        visible: false,
        source: new ol.source.TileImage({url: 'https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}'}),
    });

    var googleLayerHybrid2 = new ol.layer.Tile({
        title: "Google Terrain & Roads",
        type: 'base',
        visible: false,
        source: new ol.source.TileImage({url: 'https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}'}),
    });

    var osmLayer = new ol.layer.Tile({
        title: "Open Street Map",
        type: 'base',
        visible: true,
        source: new ol.source.OSM(),
    });

    var geofenceVectorLayerEditGeofence = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: []
        }),
    });
    var mapEditGeofence;
    var typeSelect = document.getElementById('type');
    var draw; // global so we can remove it later


    function addInteraction() {
        var value = typeSelect.value;
        if (value !== 'None') {
            draw = new ol.interaction.Draw({
                source: geofenceVectorLayerEditGeofence.getSource(),
                type: typeSelect.value
            });
            mapEditGeofence.addInteraction(draw);
        }

        draw.on('drawstart', function () {
            geofenceVectorLayerEditGeofence.getSource().clear();
        });

        draw.on('drawend', function (evt) {
            let feature = evt.feature;
            let geometry = feature.getGeometry();

            let wkt = geometryToWkt(mapEditGeofence.getView().getProjection(), geometry);
            $("#geofence_area").html(wkt);

            feature = new ol.Feature(wktToGeometry(mapEditGeofence.getView(), wkt));
            geofenceVectorLayerEditGeofence.getSource().addFeature(feature);
            mapEditGeofence.getView().fit(geofenceVectorLayerEditGeofence.getSource().getExtent());
        });
    }

    function createPicker(source){
        let picker = new CP(source);
        // prevent showing native color picker panel
        source.onclick = function(e) {
            e.preventDefault();
        };
        picker.on("change", function(color) {
            this.source.value = '#' + color;
        });
    }

    function initEditMapGeofence() {
        mapEditGeofence = new ol.Map({
            target: 'points-interest',
            layers: [
                new ol.layer.Group({
                    'title': 'Base maps',
                    layers: [
                        googleLayerHybrid,
                        googleLayerHybrid2,
                        googleLayerRoadmap,
                        osmLayer
                    ]
                })
            ],
            view: new ol.View({
                center: ol.proj.fromLonLat([-72, 4]),
                zoom: 6,
                minZoom: 0,
                maxZoom: 19,
            })
        });

        mapEditGeofence.addLayer(geofenceVectorLayerEditGeofence);

        var layerSwitcherEditGeofence = new ol.control.LayerSwitcher({
            tipLabel: 'Leyenda'
        });
        mapEditGeofence.addControl(layerSwitcherEditGeofence);
        let attributes = {
            color: "#2980b9",
            border_color: "#3498db",
            stroke_width: Traccar.Style.mapGeofenceWidth,
            fill_opacity: Traccar.Style.mapGeofenceOverlayOpacity * 100
        };
        <% if !@points_interest.new_record? %>
          let wkt = "<%= @points_interest.area %>";

          let feature = new ol.Feature(wktToGeometry(mapEditGeofence.getView(), wkt));
          attributes = <%= @points_interest.attributes["attributes"].blank? ? "{}" : @points_interest.attributes["attributes"].html_safe %>;
          feature.setStyle(geofenceStyle('<%= @points_interest.name %>', attributes ? attributes : null));
          feature.geofence_id = <%= @points_interest.id %>;

          geofenceVectorLayerEditGeofence.getSource().addFeature(feature);
          mapEditGeofence.getView().fit(geofenceVectorLayerEditGeofence.getSource().getExtent());
        <% end %>

        typeSelect.onchange = function() {
            mapEditGeofence.removeInteraction(draw);
            addInteraction();
        };

        addInteraction();
        let source = document.querySelector('#geofence_color');
        source.value = attributes.color;
        createPicker(source);

        source = document.querySelector('#geofence_border_color');
        source.value = attributes.border_color;
        createPicker(source);

        $("#geofence_stroke_width").val(attributes.stroke_width);
        $("#geofence_fill_opacity").val(attributes.fill_opacity);
    }

    setTimeout("initEditMapGeofence()", 500);
    hideLoadingImg();

    $('#form_points_modal').on("hidden.bs.modal", function () {
        showLoadingImg();
        $.get("<%= params[:url_refresh].blank? ? points_interest_index_path : params[:url_refresh] %>.js?<%= request.query_parameters.to_query %>", function () {
            hideLoadingImg();
            loadHideColumnSelectorTable();
        });
    });

    $(".btn.btn-send").click(function () {
        showLoadingImg();
    });
</script>

<style>
  .modal-body {
    overflow-y: auto;
    overflow-x: hidden;
    padding: 0;
  }
</style>
