if(window.location.pathname.split("/")[1] === "expert")
  window.IMApiBase = '/expert/im';
else
  window.IMApiBase = '/user/im';

window.im = io(`https://gims.gurulize.com/${domain}`, {
  query: {
  }
});

if (document.body.classList.contains('loggedIn')) {
  window.im.on("connect", () => {
    console.log("IMid-> " + im.id)
    fetch(`${window.IMApiBase}/registerme/${im.id}`, {headers: {'X-Requested-With': 'XMLHttpRequest'}})
      .then(response => response.json())
      .then(data => {
        if (!data.success) {
          console.error(data.message);
          window.im.disconnect();
        }
      });
  });
}

window.im.on('Alert', function (msg) {
  alert(msg)
});

/** mesajlasma ile ilgili */
window.im.on('IMmessage', function (d) {
  const irc = document.getElementById("im-room-content");
  if (irc) {
    document.querySelector(`.im-room-list-item[data-room-id="${d.room}"] .im-room-list-item-lastmsg`).innerHTML = d.m

    if (irc.dataset.activeRoom == d.room) {
      irc.innerHTML += printmessage({date: Date.now(), sender:d.s, id:d.id, type:d.t, message:d.m}, new Date())[1];

      document.getElementById(`rcmid${d.id}`).scrollIntoView(false);

      fetch(`${window.IMApiBase}/seen/${irc.dataset.activeRoom}`, {headers: {'X-Requested-With': 'XMLHttpRequest'}})
                .then(response => response.json())
                .then(data => {
                  if (!data.success) {
                    if(data.code == 1)
                      window.location.href = '/login'
                    else
                      alert(data.message);
                  }
              });
    } else {
      let r = document.querySelector(`.im-room-list-item[data-room-id="${d.room}"] .IMwmb`);

      let cnt = r.innerHTML * 1;
      r.innerHTML = cnt + 1;

      let cnt2 = document.getElementById("IMwaitingMessage").innerHTML * 1;
      let netCount = cnt2 + 1;
      document.getElementById("IMwaitingMessage").innerHTML = netCount;

      if(document.getElementById("IMwaitingMessageTop")){
        document.getElementById("IMwaitingMessageTop").innerHTML = netCount;
      }
    }
  } else {
    let cnt = document.getElementById("IMwaitingMessage").innerHTML * 1;
    let netCount = cnt + 1;
    document.getElementById("IMwaitingMessage").innerHTML = netCount;

    if(document.getElementById("IMwaitingMessageTop")){
      document.getElementById("IMwaitingMessageTop").innerHTML = netCount;
    }
  }
});

/** onyuz islemleri */
function reRender() {
  let activeRoom = document.getElementById("im-room-content").dataset.activeRoom;

  if (activeRoom > 0) {
    document.getElementById("im-new-message-block").style.display = "flex";

    document.getElementById("im-area-left").classList.remove("im-util-rl-show");
    document.getElementById("im-area-right").classList.remove("im-util-rl-show");
    document.getElementById("im-back-to-room-list").classList.remove("im-util-rl-show");

    document.getElementById("im-area-left").classList.add("im-util-rl-hide");
    document.getElementById("im-area-right").classList.add("im-util-rl-hide");
    document.getElementById("im-back-to-room-list").classList.add("im-util-rl-hide");
  }

  let activeRoomElement = document.querySelector(`.im-room-list-item[data-room-id="${activeRoom}"]`);

  document.querySelectorAll('.im-room-list-item').forEach(item => {
    item.style.backgroundColor = null;
  });

  if (activeRoomElement) {
    activeRoomElement.style.backgroundColor = "#F1F4F6";

    document.getElementById("im-content-room-name").innerHTML = activeRoomElement.dataset.roomName
    document.getElementById("im-content-room-img").src = activeRoomElement.dataset.roomImg
  }
}

window.addEventListener("load", (event) => {
  if (document.body.classList.contains('loggedIn')) {

    document.getElementById("im-room-list") && loadroomlist();

    (function () {
      fetch(`${window.IMApiBase}/unseen`, {headers: {'X-Requested-With': 'XMLHttpRequest'}})
        .then(response => response.json())
        .then(data => {
          if (!data.success) {
            if(data.code == 1)
              window.location.href = '/login'
            else
              alert(data.message);
          } else {
            let tot = 0;
            data.data.forEach(d => {
              tot += d.count*1;
              
              let r = document.querySelector(`.im-room-list-item[data-room-id="${d.room}"] .IMwmb`);
              
              if (r) {
                r.innerHTML = d.count;
              }
            });

            document.getElementById("IMwaitingMessage").innerHTML = (tot != 0)?tot:"";
            document.getElementById("IMwaitingMessageTop") && 
            (document.getElementById("IMwaitingMessageTop").innerHTML = (tot != 0)?tot:"");
          }
        });
    })();
  } else {
    console.log("not Logged In")
  }
});

function delmessage(id) {
  fetch(`${window.IMApiBase}/del/${id}`, {headers: {'X-Requested-With': 'XMLHttpRequest'}})
      .then(response => response.json())
      .then(data => {
          if (!data.success) {
            if(data.code == 1)
              window.location.href = '/login'
            else
              alert(data.message);
          } else {
              loadRoomContent(data.room)
          }
      });
}

function printmessage({date, sender, id, message, type}, lastDate) {

  let msgDate = new Date(date);
  const tzopt = { timeZone: window.IMtz };

  let msgDateDiv = "";
  if (lastDate.toLocaleDateString() !== msgDate.toLocaleDateString()) {
    msgDateDiv = `<div><div class="im-content-date-divider">${msgDate.toLocaleDateString(new Intl.Locale(navigator.languages[0]), tzopt)}</div></div>`;
    lastDate = msgDate;
  }

  return [lastDate, 
          `${msgDateDiv}
          <div style="display:flex; ${(window.IMme == sender ? "justify-content: end;" : "")}">
            <div data-before="${type == 2 ? __('im-automatic-message') : ""}" id="rcmid${id}" class="im-content-message ${(window.IMme == sender ? "im-from-me" : "im-from-other")} im-msgtype-${type}">
              <div>${message}</div>
              <div class="im-content-date">${msgDate.toLocaleTimeString(new Intl.Locale(navigator.languages[0]), tzopt)}</div>
            </div>
          </div>`]
}

function loadRoomContent(room) {
  const rc = document.getElementById("im-room-content");

  rc.dataset.activeRoom = room;
  reRender();

  fetch(`${window.IMApiBase}/roomcontent/${room}`, {headers: {'X-Requested-With': 'XMLHttpRequest'}})
      .then(response => response.json())
      .then(data => {
          if (!data.success) {
            if(data.code == 1)
              window.location.href = '/login'
            else
              alert(data.message);
          } else {
              if (data.data.length > 0) {
                
                  let lastDate = new Date(2000, 1);
                  rc.innerHTML = data.data.map((m) => { [lastDate, cntnt] = printmessage(m, lastDate); return cntnt;}).join("");
                      
                  const mid = Math.max(...data.data.map(o => o.id))
                  document.getElementById(`rcmid${mid}`).scrollIntoView(false);

                  let roomIMwmb = document.querySelector(`.im-room-list-item[data-room-id="${room}"] .IMwmb`);

                  let roomIMwmbcnt = roomIMwmb.innerHTML * 1;
            
                  let cnt2 = document.getElementById("IMwaitingMessage").innerHTML * 1;
                  let netCount = cnt2 - roomIMwmbcnt;
                  document.getElementById("IMwaitingMessage").innerHTML = (netCount != 0 ? netCount : "");

                  if(document.getElementById("IMwaitingMessageTop")) {
                    document.getElementById("IMwaitingMessageTop").innerHTML = (netCount != 0 ? netCount : "");
                  }

                  roomIMwmb.innerHTML = "";
              } else {
                  rc.innerHTML = "No message here";
              }

              $('#im-area-right').css('display','flex');
          }
      });
}

async function loadroomlist() {
  await fetch(`${window.IMApiBase}/roomlist`, {headers: {'X-Requested-With': 'XMLHttpRequest'}})
      .then(response => response.json())
      .then(data => {
          if (!data.success) {
            if(data.code == 1)
              window.location.href = '/login'
            else
              alert(data.message);
          } else {
              var rl = data.rooms.map((r) => `
          <div class="im-room-list-item" data-room-id="${r.id}" data-room-name="${r.name}" data-room-img="${r.img}">
              <img onerror="this.src='/common/user-circle-solid.svg';" src="${r.img}">
              <div class="im-name-container">
                  <span class="im-room-list-item-name">${r.name}</span><span class="IMwmb im-badge-user-list"></span>
                  <div class="im-room-list-item-lastmsg">${r.message ? r.message : ''}</div>
                </div>
              <span class="im-room-list-item-time"> ${r.date ? ('0'+(new Date(r.date)).getHours()).slice(-2) +':'+ ('0'+(new Date(r.date)).getMinutes()).slice(-2) : ''} </span>

              <span class="position-absolute top-0 end-0  p-0  text-light ${r.userType==0?`bg-dark`:``} ${r.userType==2?`bg-success`:``}  ${r.userType==1?`bg-primary`:``} border border-light rounded-pill" style="font-size: x-small;padding: 1px 6px !important;">${r.userType==2?__('user'):``}${r.userType==1?__('agent'):``}${r.userType==0?__('manager'):``}</span>

            </div>
          `
              ).join("");

              document.getElementById("im-room-list").innerHTML = rl;

              document.querySelectorAll('.im-room-list-item').forEach(item => {
                  item.addEventListener('click', function (event) {
                      loadRoomContent(this.dataset.roomId)
                  });
              });

              $('.im-room-list-item[data-room-id='+new URLSearchParams(window.location.search).get('id')+']').click();
          }
      });
};

document.getElementById("im-new-message") &&
document.getElementById("im-new-message").addEventListener("keypress", function(event) {
  if (event.key === "Enter") {
      event.preventDefault();
      document.getElementById("im-new-send-btn").click();
  }
});

document.getElementById("im-new-send-btn") &&
document.getElementById("im-new-send-btn").addEventListener('click', function (event) {
    fetch(`${window.IMApiBase}/newmessage/${document.getElementById("im-room-content").dataset.activeRoom}`,
        {
            method: "POST",
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            body: `${document.getElementById("im-new-message").value}`
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
              if(data.code == 1)
                window.location.href = '/login'
              else
                alert(data.message);
            } else {
                document.getElementById("im-new-message").value = '';
            }
        });
});

document.getElementById("im-back-to-room-list") &&
document.getElementById("im-back-to-room-list").addEventListener('click', function (event) {

    document.getElementById("im-area-left").classList.add("im-util-rl-show");
    document.getElementById("im-area-right").classList.add("im-util-rl-show");
    document.getElementById("im-back-to-room-list").classList.add("im-util-rl-show");
    document.getElementById("im-area-left").classList.remove("im-util-rl-hide");
    document.getElementById("im-area-right").classList.remove("im-util-rl-hide");
    document.getElementById("im-back-to-room-list").classList.remove("im-util-rl-hide");
});
