<div class="modal fade" id="form_geofence_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"><%= t("activerecord.models.geofence") %></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: @geofence, remote: true) do |form| %>
          <div style="width: 100%; height: 400px;" id="map-edit-geofence"></div>
          <div class="field">
            <div class="row">
              <div class="col-md-12 col-xs-12 col-sm-12 px-7">
                <%= form.label t("activerecord.attributes.traccar/geofence.type") %>
              </div>
            </div>
            <div class="row">
              <div class="col-md-12 col-xs-12 col-sm-12 px-7">
                <select id="type">
                  <option value="Polygon"><%= _("Polygon") %></option>
                  <option value="Circle"><%= _("Circle") %></option>
                  <option value="LineString"><%= _("LineString") %></option>
                </select>
              </div>
            </div>
          </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", required: true %>
              </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", required: true %>
              </div>
            </div>
          </div>

          <div class="field">
            <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", required: true %>
              </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 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 = getMapInstance('map-edit-geofence', null);
        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 !@geofence.new_record? %>
          let wkt = "<%= @geofence.area %>";

          let feature = new ol.Feature(wktToGeometry(mapEditGeofence.getView(), wkt));
          attributes = <%= @geofence.attributes["attributes"].blank? ? "{}" : @geofence.attributes["attributes"].html_safe %>;
          feature.setStyle(geofenceStyle('<%= @geofence.name %>', attributes ? attributes : null));
          feature.geofence_id = <%= @geofence.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_geofence_modal').on("hidden.bs.modal", function () {
        showLoadingImg();
        $.get("<%= params[:url_refresh].blank? ? geofences_path : params[:url_refresh] %>.js?<%= request.query_parameters.to_query %>", function () {
            hideLoadingImg();
            loadHideColumnSelectorTable();
        });
    });

    $(".btn.btn-send").click(function () {
        showLoadingImg();
    });
</script>

<style>
  .modal-dialog{
    min-width: 800px;
  }
  .modal-body {
    overflow-y: auto;
    overflow-x: hidden;
    padding: 0;
    margin-left: 0px;
    min-width: 800px;
  }
</style>
