"use strict";
(async function () {
  let
    control_approve = document.getElementById("Approve"),
    control_communicationRoomId = document.getElementById("CommunicationRoomId"),
    control_communicationUserId = document.getElementById("CommunicationUserId"),
    control_communicationUserToken = document.getElementById("CommunicationUserToken"),
    control_displayName = document.getElementById("DisplayName"),
    control_draggableModal = document.getElementById("DraggableModal"),
    control_identificationImage = document.getElementById("IdentificationImage"),
    control_otpForm = document.getElementById("OtpForm"),
    control_participantListGroup = document.getElementById("ParticipantListGroup"),
    control_participants = document.getElementById("Participants"),
    control_participantType = document.getElementById("ParticipantType"),
    control_pdfViewer = document.getElementById("PdfViewer"),
    control_reject = document.getElementById("Reject"),
    control_rightSidebarModal = document.getElementById("RightSidebarModal"),
    control_selfieImage = document.getElementById("SelfieImage"),
    control_serverCallIID = document.getElementById("ServerCallID"),
    control_signatoryName = document.getElementById("SignatoryName"),
    control_templateParticipantItem = document.getElementById("TemplateParticipantItem"),
    control_templateSidePane = document.getElementById("TemplateSidePane"),
    control_videoGridContainer = document.getElementById("videoGrid-container"),
    control_viewDocument = document.getElementById("ViewDocument"),
    x = 1;

  let participants = JSON.parse(control_participants.value);

  async function _initVideoCall() {
    let self = this;
    let customButtons = [];
    if (control_participantType.value == 'Notary') {
      customButtons = [
        function (args) {
          return {
            placement: 'secondary',
            // Icon registered by the composites.
            iconName: 'OpenAttachment',
            strings: {
              label: 'View Document',
              tooltipContent: 'View the document.'
            },
            onItemClick: function () {
              const modal = bootstrap.Modal.getOrCreateInstance(control_pdfViewer);
              modal.show();
            }
          };
        },
        function (args) {
          return {
            placement: 'primary',
            strings: {
              label: 'OTP',
              tooltipContent: 'Enter your OTP'
            },
            onItemClick: function () {
              const modal = bootstrap.Modal.getOrCreateInstance(control_otpForm);
              modal.show();
            }
          };
        },
        function (args) {
          return {
            placement: 'secondary',
            // Icon registered by the composites.
            iconName: 'ControlButtonParticipantsContextualMenuItem',
            strings: {
              label: 'View Participants',
              tooltipContent: 'View the participants.'
            },
            onItemClick: function () {
              const modal = bootstrap.Modal.getOrCreateInstance(control_rightSidebarModal);
              modal.show();
            }
          };
        },
        function (args, b, c) {
          return {
            placement: 'primary',
            // Icon registered by the composites.
            iconName: 'EditBoxSubmit',
            strings: {
              label: 'Approve',
              tooltipContent: 'Approve the Transaction'
            },
            onItemClick: approveTransaction
          };
        },
        function (args, b, c) {
          return {
            placement: 'primary',
            // Icon registered by the composites.
            iconName: 'EditBoxCancel',
            strings: {
              label: 'Reject',
              tooltipContent: 'Reject the Transaction'
            },
            onItemClick: function () {
              alert('Rejected!');
            }
          };
        }
      ];
    } else {
      customButtons = [
        function (args) {
          return {
            placement: 'primary',
            // Icon registered by the composites.
            iconName: 'OpenAttachment',
            strings: {
              label: 'View Document',
              tooltipContent: 'View the document.'
            },
            onItemClick: function () {
              alert('Document Modal goes here.');
            }
          };
        },
        function (args) {
          return {
            placement: 'secondary',
            // Icon registered by the composites.
            iconName: 'OpenAttachment',
            strings: {
              label: 'View Document',
              tooltipContent: 'View the document.'
            },
            onItemClick: function () {
              alert('Document Modal goes here.');
            }
          };
        },
      ];
    }

    const videoCall = jfa.communication.videocall;
    let options = {
      //onCreateLocalVideoStream: function (el) {
      //  if (el) {
      //    el.style['transform'] = '';
      //    let notary = participants.find(p => p.RoomUserID == control_communicationUserId.value);
      //    document.getElementById(notary.Id).appendChild(el);
      //  }
      //},
      //remoteVideoIsAvailableChanged: function (e) {
      //  let participant = participants.find(p => p.RoomUserID == e.participantId);
      //  if (participant) {
      //    e.el.querySelector('video').style['object-fit'] = 'cover';
      //    document.getElementById(participant.Id).appendChild(e.el);
      //  }
      //},
      onGetServerCallIDCallback: function (serverCallId) {
        //  let url = jfa.utilities.routing.getCurrentURLWithHandler("StartRecording");
        //  url.searchParams.append("ServerCallID", serverCallId);
        //  jfa.utilities.request.post(url, {})
        //    .then(resp => {
        //      if (resp.ok === true) {
        //        console.log("started recording");
        //      }
        //    })
        //    .catch(err => console.error(err));
        //debugger;
      },
      stateChangedCallback: function (state) {
        //console.log(state);
      },
      onFetchParticipantMenuItemsCallback: function (participantUserId, userId, defaultMenuItems) {
        const participantList = document.querySelector('[data-ui-id="people-pane-content"]');
        if (participantList) {
          participantList.innerHTML = '';
          console.log(participants);
        }
        defaultMenuItems = [];
      },
      onFetchCustomButtonPropsCallbacks: customButtons,
      onAddParticipantCallback: function (e, f) {
        //debugger;
        console.log(e, f);
      },
      participantsJoinedCallback: function (e, f) {
        //debugger;
        console.log(e, f);
      },
      callEndedCallback: function (a, b, c) {
      },
      token: control_communicationUserToken.value,
      roomID: control_communicationRoomId.value,
      displayName: control_displayName.value,
      userID: control_communicationUserId.value,
      videoContainer: control_videoGridContainer
    };
    await videoCall.init(options);
    await videoCall.joinRoom();
  }

  function approveTransaction(e) {
    let url = jfa.utilities.routing.getCurrentURLWithHandler("Approve");
    jfa.utilities.request.post(url, {})
      .then(resp => {
        if (resp.ok === true) {
          jfa.communication.videocall.stopCall(true);
        }
      })
      .catch(err => console.error(err));
  }

  function _createParticipantListItems() {
    control_participantListGroup.innerHTML = '';
    participants.forEach(participant => {
      if (participant.Type === 'Notary') {
        return;
      }
      const initials = participant.DisplayName.split(' ').map(n => n.charAt(0)).join('');
      let tmpl = control_templateParticipantItem.cloneNode(true).content;
      tmpl.querySelector('.participant-item').dataset.participantUid = participant.RoomUserID;
      tmpl.querySelector('.participant-item').dataset.participantUid = participant.UID;
      tmpl.querySelector('.participant-avatar').textContent = initials;
      tmpl.querySelector('.participant-name').textContent = participant.DisplayName;
      control_participantListGroup.appendChild(tmpl);
    });
  }

  function _bindEvents() {
    control_participantListGroup.addEventListener('click', function (event) {
      let target = event.target?.closest('.list-group-item');
      if (target) {
        const participant = participants.find(p => p.UID == target.dataset.participantUid);
        if (!participant) {
          return;
        }
        control_signatoryName.textContent = participant.DisplayName;

        let selfieUrl = jfa.utilities.routing.getCurrentURLWithHandler("SelfieImage");
        selfieUrl.searchParams.append("meetingRoomUserID", participant.RoomUserID);

        let identificationUrl = jfa.utilities.routing.getCurrentURLWithHandler("IdentificationDocument");
        identificationUrl.searchParams.append("meetingRoomUserID", participant.RoomUserID);
        control_selfieImage.src = selfieUrl;

        const sidebarModal = bootstrap.Modal.getOrCreateInstance(control_rightSidebarModal);
        sidebarModal.hide();
        control_identificationImage.src = identificationUrl;

        const draggableModal = bootstrap.Modal.getOrCreateInstance(control_draggableModal);
        draggableModal.show();
      }
    });

    control_draggableModal.addEventListener('shown.bs.modal', function (e) {
      makeDraggable(control_draggableModal);
    });
  }

  function makeDraggable(modal) {
    let isDragging = false;
    let offsetX, offsetY;

    const header = modal.querySelector('.modal-header');

    header.addEventListener('mousedown', (e) => {
      isDragging = true;
      offsetX = e.clientX - modal.offsetLeft;
      offsetY = e.clientY - modal.offsetTop;
    });

    document.addEventListener('mousemove', (e) => {
      if (!isDragging) return;
      modal.style.left = `${e.clientX - offsetX}px`;
      modal.style.top = `${e.clientY - offsetY}px`;
    });

    document.addEventListener('mouseup', () => {
      isDragging = false;
    });
  }

  async function _init() {
    _bindEvents();
    await _initVideoCall();
    _createParticipantListItems();
  }

  await _init();
})();