<div id="contacts" class="page-layout simple left-sidebar-floating">
  <div class="page-content-wrapper">
    <aside class="col-sm-12 col-md-3 col-lg-3 col-xl-3" data-fuse-bar="contacts-sidebar" data-fuse-bar-media-step="md" style="padding: 0;">
      <div class="page-sidebar-card">
        <!-- SIDENAV CONTENT -->
        <div class="row" style="width: 100%;margin: 0;">
          <div class="col-md-12" style="background-color: #145784;color:white; height: 42px;padding-top: 10px;font-size: 12pt;padding-left: 26px;">
            <%= _("Geofence Tools") %>
          </div>
        </div>
        <ul style="height: 40px;border-bottom: 2px solid #145784;" class="nav nav-tabs nav_geofence_assign" id="myTab" role="tablist">
          <li class="nav-item">
            <a style="height: 100%;" class="nav-link active" id="view_geofences-tab" data-toggle="tab" href="#view_geofences" role="tab"
               aria-controls="home_vehicle" aria-expanded="true"><%= _("View") %></a>
          </li>
          <li class="nav-item">
            <a style="height: 100%;" class="nav-link" id="assign_geofences-tab" data-toggle="tab" href="#assign_geofences" role="tab"
               aria-controls="session_vehicle"><%= _("Assign") %></a>
          </li>
          <li style="margin-top: 4px">
            <%= link_to t("main.utils.add") + " " + t("activerecord.models.#{@add_button.name.underscore}"), "/" + @add_button.name.underscore.pluralize + "/new?url_refresh=" + site_user_site_user_geofences_url + "&" + request.query_parameters.to_query, {remote: true, class: "btn-filter btn btn-light btn-sm fuse-ripple-ready btn-create", style: ""} if current_user.user_admin %>
          </li>
        </ul>
        <div class="tab-content" id="myTabContent">
          <div class="tab-pane fade show active" id="view_geofences" role="tabpanel" aria-labelledby="view_geofences-tab">
            <div class="content content-table-geofences">
              <%= render "site_user/tracking/geofence/table" %>
            </div>
          </div>
          <div class="tab-pane fade" id="assign_geofences" role="tabpanel" aria-labelledby="assign_geofences-tab">
            <div id="accordion_now" role="tablist">
              <div class="card">
                <div class="card-header" role="tab" id="headingOne">
                  <h5 class="mb-0">
                    <a data-toggle="collapse" href="#general_now_map_vehicle" aria-expanded="true"
                       aria-controls="collapseOne">
                      <i class="icon-plus"></i><%= _("Item Assignment") %>
                    </a>
                  </h5>
                </div>

                <div id="general_now_map_vehicle" class="collapse show" role="tabpanel" aria-labelledby="headingOne"
                     data-parent="#accordion_now">
                  <div class="card-block">
                    <div id="vehicle-detail-map">
                      <table id="item-assignment" class="simple clickable table-striped table-hover">
                        <thead>
                        <tr>
                          <th class="text-center">
                            <%= _("Item") %>
                            <img class="loading-image" style="width: 10px;visibility: hidden;" src="<%= asset_path("others/loading.gif") %>">
                          </th>
                          <th style="width: 10px;" class="text-center">
                          </th>
                        </tr>
                        </thead>
                        <tbody>
                        <% @vehicles.each do |vehicle| %>
                          <% if vehicle.device %>
                            <tr data-marker="<%= vehicle.marker_url %>" id="device_id_<%= vehicle.tc_device_id %>">
                              <td title="offline" class="name_vehicle offline">
                                <a href="javascript:void(0)"><%= vehicle.name %></a>
                              </td>
                              <td class="text-center">
                                <a onclick="showItemGeofencesAssign(<%= vehicle.device.id %>)" href="javascript:void(0)">
                                  <i style="font-size: 14pt;" class="icon-brightness-5"></i>
                                </a>
                              </td>
                            </tr>
                          <% end %>
                        <% end %>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
              <div class="card">
                <div class="card-header" role="tab" id="headingTwo">
                  <h5 class="mb-0">
                    <a class="collapsed" data-toggle="collapse" href="#general_now_vehicle" aria-expanded="false"
                       aria-controls="collapseTwo">
                      <i class="icon-plus"></i><%= _("Geofence Assignment") %>
                    </a>
                  </h5>
                </div>
                <div id="general_now_vehicle" class="collapse" role="tabpanel" aria-labelledby="headingTwo"
                     data-parent="#accordion_now">
                  <div class="card-block">
                    <table id="geofence-name" class="table-content-crud table table-hover table-striped">
                      <thead>
                      <tr>
                        <th class="text-center">
                          <%= _("Geofence Name") %>
                          <img class="loading-image" style="width: 10px;visibility: hidden;" src="<%= asset_path("others/loading.gif") %>">
                        </th>
                        <th style="width: 30px;" class="text-center">

                        </th>
                        <th style="width: 30px;" class="text-center">
                        </th>
                      </tr>
                      </thead>
                      <tbody>
                      <% @geofences.each do |geofence| %>
                        <tr>
                          <td>
                            <img style="width: 20px;" src="<%= asset_path("others/"+ geofence.area.split("(")[0].downcase.gsub(" ", "") + ".png") %>">
                            <%= geofence.name %>
                            <textarea style="display: none;" id="geofence_<%= geofence.id %>"><%= geofence.area.html_safe %></textarea>
                          </td>
                          <td align="center">
                            <a onclick="showGeofenceAssign(<%= geofence.id %>);" href="javascript:void(0)">
                              <i style="font-size: 14pt;" class="icon-brightness-5"></i>
                            </a>
                          </td>
                          <td align="center">
                            <input id="check_geofence_<%= geofence.id %>" onchange="showGeofenceArea(this, '<%= geofence.id %>')" type="checkbox">
                          </td>
                        </tr>
                      <% end %>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
              <div class="card-block">
              </div>
            </div>
          </div>
        </div>
        <!-- / SIDENAV CONTENT -->
      </div>
    </aside>

    <!-- CONTENT -->
    <div class="col-sm-12 col-md-12 col-lg-9 col-xl-9" style="margin: 0px;padding: 0px;">
      <div class="row map-content-header" style="margin: 0px;height: 37px;border-bottom: 1px solid #045784;">
        <div class="col-8" style="background-color: #eee;">
          <button type="button" class="sidebar-toggle-button btn btn-icon d-inline-block d-lg-none mr-2" data-fuse-bar-toggle="contacts-sidebar">
            <i class="icon icon-menu"></i>
          </button>
          <i class="icon-map s-6"></i><%= _("View on map") %>
        </div>
        <div class="col-4" style="padding-top: 8px;border-right: 1px solid #045784;background-color: #eee;">
          <div align="right" style="positon: flex;">

          </div>
        </div>
      </div>
      <div class="row map-content-row" style="margin: 0px;">
        <div class="col-12" style="padding: 0px; height: 100%;">
          <div id="map" class="map"></div>
        </div>
      </div>
    </div>
    <!-- / CONTENT -->
  </div>
</div>
<div class="dinamic-content"></div>
<%= render "details_vehicle" %>

<%= stylesheet_link_tag  'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.2.1/css/ol.css' %>
<%= stylesheet_link_tag  'https://unpkg.com/ol-layerswitcher@3.5.0/src/ol-layerswitcher.css' %>

<%= javascript_include_tag 'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.2.1/build/ol.js' %>
<%= javascript_include_tag 'https://unpkg.com/ol-layerswitcher@3.5.0' %>
<%= javascript_include_tag 'map' %>
<script>
    var map;
    var geofences_info = <%= @geofences_by_id.to_json.html_safe %>;
    var geofenceVectorLayer = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: []
        }),
    });
    function initSizeMap(){
        let height_calc = $( window ).height() - $("main").position().top;
        $("main").height(height_calc);
        $("#wrapper").height(height_calc);
        $("#wrapper .content-wrapper").height(height_calc);
        $("#wrapper > .content-wrapper > .content").height(height_calc);
        $("#wrapper > .content-wrapper > .content > #contacts").height(height_calc);

        height_calc = height_calc - $(".page-content-wrapper").position().top;
        $(".page-content-wrapper").height(height_calc);

        let height_calc_map = height_calc - $(".map-content-row").position().top;
        $(".map-content-row").height(height_calc_map);
        $(".map-content-row > div").height(height_calc_map);
        $(".map-content-row > div > #map").height(height_calc_map);
    }

    function showGeofenceArea(elm, geofence_id){
      if($(elm).is(':checked')){
          let wkt = $("#geofence_" + geofence_id).html();

          let feature = new ol.Feature(wktToGeometry(map.getView(), wkt));
          let attributes = JSON.parse(geofences_info[geofence_id]["attributes"]["attributes"]);
          feature.setStyle(geofenceStyle(geofences_info[geofence_id]['name'], attributes ? attributes : null));
          feature.geofence_id = geofence_id;

          geofenceVectorLayer.getSource().addFeature(feature);
      }else{
          removeFeatureGeofence(geofence_id);
      }

      map.getView().fit(geofenceVectorLayer.getSource().getExtent());
    }

    function getFeatureGeofence(geofence_id){
        let features =  geofenceVectorLayer.getSource().getFeatures();
        for(let i in features){
            let feature = features[i];
            if(feature.geofence_id == geofence_id)
                return feature;
        }
        return null;
    }

    function removeFeatureGeofence(geofence_id){
        let feature = getFeatureGeofence(geofence_id);
        if(feature)
            geofenceVectorLayer.getSource().removeFeature(feature);
    }

    function initMapGeofence(){
        initSizeMap();
        map = getMapInstance('map', null);
        map.addLayer(geofenceVectorLayer);

        var layerSwitcher = new ol.control.LayerSwitcher({
            tipLabel: 'Leyenda'
        });
        map.addControl(layerSwitcher);

        setTimeout("$('aside').click();", 500);

        $(window).trigger('resize');
        $(window).bind('resize', initSizeMap);
    }
    initMapGeofence();

    $(".nav_geofence_assign > li > a").click(function(){
        $("input[type='checkbox']:checked").click();
    })

    function showGeofenceAssign(id){
      $.get("/geofences/" + id + "/list_assign_to_devices", function(data){
        //console.log(data);
      });
    }

    function showItemGeofencesAssign(id){
      $.get("/geofences/list_assign_geofences_to_device/" + id, function(data){
        //console.log(data);
      });
    }
    var filtersConfig = {
        // instruct TableFilter location to import ressources from
        base_path: 'https://unpkg.com/tablefilter@0.6.102/dist/tablefilter/',
        highlight_keywords: true,
        alternate_rows: true,
        rows_counter: true,
        btn_reset: true,
        status_bar: true,
        popup_filters: true,
        enable_empty_option: true,
        enable_non_empty_option: true,
        auto_filter: {
            delay: 1100 //milliseconds
        },
        paging: {
            length: 10
        },
        // theme
        themes: [{ name: 'default' }],
        col_widths:[
            '60px'
        ],
        extensions: [{ name: 'sort' }]
    };
    var tf = new TableFilter('item-assignment', filtersConfig);
    try{
        tf.init();
    }catch (e) {

    }
    var gn = new TableFilter('geofence-name', filtersConfig);
    try{
        gn.init();
    }catch (e) {

    }
</script>

<style>

  table thead tr th {
    height: 35px;
  }

  .rdiv{
    display: none;
  }
  .mdiv{
    width: 300px;
  }
</style>
