<div class="page-header bg-primary text-auto row no-gutters align-items-center justify-content-between p-4 p-sm-6">

  <div class="col">

    <div class="row no-gutters align-items-center flex-nowrap">

      <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>

      <!-- APP TITLE -->
      <div class="logo row no-gutters align-items-center flex-nowrap">
                                      <span class="logo-icon mr-4">
                                          <i class="icon-map s-6"></i>
                                      </span>
        <span class="logo-text h4">Monitoring</span>
      </div>

    </div>
    <!-- / APP TITLE -->
  </div>

</div>
<table id="monitoring" class="hardware_profiles_table table-content-crud table table-hover table-striped">
  <thead>
  <tr>
    <th></th>
    <th><%= _("Id devise") %></th>
    <th><%= _("Customer name") %></th>
    <th><%= _("Group") %></th>
    <th><%= _("Profile") %></th>
    <th><%= _("Alert") %></th>
    <th><%= _("Item") %></th>
    <th><%= _("Date Received") %></th>
    <th><%= _("Device date") %></th>
  </tr>
  </thead>
  <tbody>
  <% @cases.each do |_case| %>
    <tr>
      <td>
        <%= link_to site_monitoring_new_case_path(_case.id), remote: true, method: :get do %>
          <div align="center">
            <i style="font-size: 15px;color: red;" class="icon icon-alert"></i>
          </div>
        <% end %>
      </td>
      <td><%= _case.device.uniqueid %></td>
      <td>
        <% if !_case.device.client.is_active? %>
          <i class="fas fa-bell-slash" style="color: red;font-size: 20px" title="<%= _('Disabled client') %>"></i>
        <% end %>
        <%= _case.device.client.full_name %>
      </td>
      <td><%= _case.device.get_vehicle.group.name %></td>
      <td><%= _case.device.hardware_profile.name %></td>
      <td><%=( _case.position.get_event_type_name.present?)?  _case.position.get_event_type_name : _case.name %></td>
      <td><%= _case.device.get_vehicle.name %></td>
      <td><%= _case.date %></td>
      <td><%= _case.position.devicetime %></td>
    </tr>
  <% end %>
  </tbody>
</table>
<%= javascript_include_tag "map" %>
<script>

    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,
        paging: {
            length: 30
        },
        enable_empty_option: true,
        enable_non_empty_option: true,
        auto_filter: {
            delay: 1100 //milliseconds
        },
        // theme
        themes: [{ name: 'default' }],
        col_widths:[
            '60px'
        ],
        extensions: [{ name: 'sort' }]
    };

    var tf = new TableFilter('monitoring', filtersConfig);
    try{
        tf.init();
    }catch (e) {

    }


    var global_geofences = <%= @geofences.to_json.html_safe %>;
    var global_vehicles_by_device_id = <%= @vechicles_by_id.to_json.html_safe %>;
    function getNameGeofenceById(id) {
        for (let i in global_geofences) {
            if (global_geofences[i].id == id)
                return global_geofences[i].name;
        }
        return "";
    }
    var infoDevices;
    function startSocketWithServerTracking() {
        infoDevices = new WebSocket("<%= ENV["TRACCAR_SERVER_SOCKET_URI"] %>");
        infoDevices.onmessage = function (msg) {
            let data = JSON.parse(msg.data);
            if (data.events) {
                console.log(data);
                for (let key in data.events) {
                    let audio = document.createElement("audio");
                    if (data.events[key].sound) {
                        audio.src = "/assets/sounds/" + data.events[key].sound + ".mp3";
                        audio.loop = true;
                    }
                    let title = 'Nueva notificación!';
                    let name_alert = data.events[key].name_alert;
                    let name_geofence = getNameGeofenceById(data.events[key].geofenceId);
                    name_alert = name_alert + (name_geofence ? "-----> Geocerca: " + name_geofence : "");
                    let text = "Alerta de tipo: " + name_alert + " para el dispositivo: " + global_vehicles_by_device_id[data.events[key].deviceId];
                    showStackBarAlert(data.events[key].color_alert, title, text, audio, true);
                }
            }
        }
    }

    function startSessionServerTracking() {
        $.ajax({
            url: "<%= ENV["TRACCAR_SERVER_URI"] %>/api/session?token=<%= current_user.token %>",
            data: {},
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: function (data) {
                $(".loading-image").css("visibility", "hidden");
                startSocketWithServerTracking();
            }
        });
        /*$.ajax({
            url: "<%= ENV["TRACCAR_SERVER_URI"] %>/api/session",
            data: {},
            type: 'DELETE',
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: function (data) {
                $.ajax({
                    url: "<%= ENV["TRACCAR_SERVER_URI"] %>/api/session?token=<%= current_user.token %>",
                    data: {},
                    dataType: 'json',
                    xhrFields: {
                        withCredentials: true
                    },
                    success: function (data) {
                        $(".loading-image").css("visibility", "hidden");
                        startSocketWithServerTracking();
                    }
                });
            },
            error: function (error) {
                $.ajax({
                    url: "<%= ENV["TRACCAR_SERVER_URI"] %>/api/session?token=<%= current_user.token %>",
                    data: {},
                    dataType: 'json',
                    xhrFields: {
                        withCredentials: true
                    },
                    success: function (data) {
                        $(".loading-image").css("visibility", "hidden");
                        startSocketWithServerTracking();
                    }
                });
            }
        });*/
    }

    function init() {
        startSessionServerTracking();
    }

    init();

    function stopTraccar(){
        infoDevices.close();
    }

    function reconnectTraccar(){
        stopTraccar();
        startSessionServerTracking();
    }
    setTimeout("reconnectTraccar()", 40000);
</script>
