document.addEventListener('DOMContentLoaded', function() {

  const url = `${window.location.origin}`;
  const siteUrl = window.location.origin;

  const bugID = location.href.split('=')[1];
  const email = document.querySelector('#useremail').className;
  const workTime = document.querySelector('#timespent').value;

  const socket = io.connect(url, {'forceNew': true});

  let userToken = !localStorage[siteUrl] ? undefined : JSON.parse(localStorage[siteUrl]).userToken;

  socket.emit('addUser', { bugID: bugID, email: email, workTime: workTime });

  function showUser (data) {

    let workerEmail = data.email;
    let workerId = data.id;
    let workersList = document.querySelector("#workers").innerHTML !== "" ? Array.from(document.querySelectorAll("#workers > a")).map((elem) => { return elem.dataset["email"] }) : undefined;

    if (!workersList || !workersList.includes(workerEmail)) {
      fetch(`https://bugs.etersoft.ru/rest/user/${workerEmail}`).then((name) => { return name.json() }).then((name) => {
        name = name.users[0].real_name;
        let worker = `
          <a href="maito:${workerEmail}" id="${workerId}" data-email="${workerEmail}" title="${name}">${name}</a><span class="worker ${workerId}"></span>
        `;

        document.querySelector("#workers").innerHTML += worker;
      });
    }
  }

  socket.on('showAllUsers', function (data) {
    if (data[bugID] !== undefined) {

      for (worker in data[bugID]) {
        let user = { id: worker, email: data[bugID][worker] }

        showUser(user);
      }
    }
  })

  socket.on('deleteUser', function (data) {
    let id = data.id;
    let email = data.email;

    if (document.getElementById(id)) {
      document.getElementById(id).remove();
      document.querySelector(`.${id}`).remove();
    }
  })

});

