{% extends "base.html" %}

{% block header %}
<header id="negotiation-header">
  <div class="inner">
    <nav id="navigation">
      <span id="home-button" class="nav-button">
        <a class="home-button"><i class="ic ic-settings"></i>Settings</a>
      </span>
      <h1 class="post-title">Red Markets Negotiations: {{ negotiation.name }}</h1>
      <span id="menu-button" class="nav-button">
        <a class="menu-button"><i class="ic ic-menu"></i> Menu</a>
      </span>
    </nav>
  </div>
</header>
{% endblock header %}

{% block content %}
<div id="negotiation" class="negotiation-wrapper">
  <div class="negotiation-sidebar">{% include 'partials/negotiation-sidebar.html' %}</div>
  <div class="negotiation-panel">{% include 'partials/negotiation-panel.html' %}</div>
</div>
<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
  // const negotiation = new Negotiation("{{negotiation.name}}")
  var socket = io();
  var room = "{{negotiation.name}}";
  socket.on('connect', function() {
      console.log("Trying to join room " + room);
      socket.emit('join negotiation', {"room": room});
  });
  window.addEventListener('beforeunload', function(e) {
      console.log("Trying to leave room " + room);
      socket.emit('leave negotiation', {"room": room});
      socket.disconnect();
      return true;
  });
  socket.on('participants changed', (data) => {
      console.log(data);
      $("#negotiation .participants .count").html(data['participants'].length);
      $("#negotiation .participant-list li").each(function() {
          if (!data['participants'].includes($(this).attr('participant-id'))) {
              console.log("Removing element for participant id " + $(this).attr('participant-id'));
              console.log($(this));
              $(this).remove();
          }
      });
      var num_p;
      var listed = $('#negotiation .participant-list li');
      for (num_p = 0; num_p < data['participants'].length ; num_p++) {
          var p = data['participants'][num_p];
          console.log('Checking to see if ' + p + ' is in the participant list');
          console.log($('#negotiation .participant-list li[participant-id="' + p + '"]'));
          if ($('#negotiation .participant-list li[participant-id="' + p + '"]').length < 1) {
              $("#negotiation .participant-list").append(
                  '<li participant-id="' + p + '">' + p + '</li>'
              );
          }
      }
  });
</script>
{% endblock content %}