var CoviewBridge = {};
var CollaborationFeature = {};

CoviewBridge.bindReadyEvent = function () {
  console.log("peacekim:: CoviewBridge.bindReadyEvent");
  coview_api.addEventListener("ready", function () {
    console.log(
      "peacekim:: CoviewBridge.bindReadyEvent coview_api.addEventListener ready"
    );
    CoviewBridge.bindFermiWebSocketOpenned();

    // add login ID if not exist
    CoviewBridge.addLoginID(globalUserInfo.loginId);
    coview_api.Login(globalUserInfo.loginId);
    CollaborationUI.updateScreen(globalUserInfo.collaborationType);
    NativeBridgeDelegate.setHostRequestFlg(HostRequestFlag.DONE);
  });
};

CoviewBridge.bindFermiWebSocketOpenned = function () {
  console.log("peacekim:: CoviewBridge.bindFermiWebSocketOpenned");
  try {
    wc_api.addEventListener("open", async function (event) {
      console.log(
        "peacekim:: CoviewBridge.bindFermiWebSocketOpenned wc_api.addEventListener open"
      );
      FermiWebSocketMessageHandler.bindWebSocketMessage();
    });
  } catch (err) {
    setTimeout(() => {
      CoviewBridge.bindFermiWebSocketOpenned();
    }, 1000);
  }
};

CoviewBridge.bindStartEvent = function () {
  console.log("peacekim:: CoviewBridge.bindStartEvent");
  coview_api.addEventListener("start", function () {
    console.log(
      "peacekim:: CoviewBridge.bindStartEvent coview_api.addEventListener(start)"
    );
    CollaborationFeature.enableScrollLock();
    CollaborationUI.hideLoadingIndicator();
  });
};

CollaborationFeature.checkAndRetryCamera = async function () {
  console.log(
    "peacekim:: CollaborationFeature.checkAndRetryCamera deviceInfo.isAndroid: " +
      deviceInfo.isAndroid() +
      ", globalUserInfo.collaborationType: " +
      globalUserInfo.collaborationType +
      ", COLLABORATION_TYPE.VIDEO: " +
      COLLABORATION_TYPE.VIDEO +
      ", g_newStream: " +
      g_newStream
  );
  if (!deviceInfo.isAndroid) {
    return;
  }
  if (globalUserInfo.collaborationType != COLLABORATION_TYPE.VIDEO) {
    return;
  }
  if (g_newStream != null) {
    return;
  }
  console.log(
    "peacekim:: CollaborationFeature.checkAndRetryCamera retry camerastream"
  );
  try {
    const cameraStream = await navigator.mediaDevices.getUserMedia(
      options.constraints
    );
    if (cameraStream != null && options.isMainMan) {
      ORGcreateLocalVideo(options.constraints);
    } else {
      setTimeout(() => {
        CollaborationFeature.checkAndRetryCamera();
      }, 1000);
    }
  } catch (error) {
    setTimeout(() => {
      CollaborationFeature.checkAndRetryCamera();
    }, 1000);
  }
};

/**************
 * Scroll Lock
 **************/
CollaborationFeature.scrollLock = function (e) {
  console.log("peacekim:: CollaborationFeature.scrollLock");
  if (deviceInfo.isiOS()) {
    if (
      $(e.target).closest(".add_user_modal").length > 0 ||
      $(e.target).closest("#overlay_user_list").length > 0 ||
      $(e.target).closest(".pip_indicator").length > 0
    ) {
      e.stopPropagation();
    } else {
      e.preventDefault();
    }
  }
};

CollaborationFeature.enableScrollLock = function () {
  console.log("peacekim:: CollaborationFeature.enableScrollLock");
  document
    .getElementById("collabo_main")
    .addEventListener("touchmove", CollaborationFeature.scrollLock, {
      passive: false,
    });
};

CollaborationFeature.disableScrollLock = function () {
  console.log("peacekim:: CollaborationFeature.disableScrollLock");
  document
    .getElementById("collabo_main")
    .removeEventListener("touchmove", CollaborationFeature.scrollLock, {
      passive: false,
    });
};

CoviewBridge.bindAllByeEvent = function () {
  console.log("peacekim:: CollaborationFeature.bindAllByeEvent");
  coview_api.addEventListener("allbye", function () {
    console.log(
      "peacekim:: CollaborationFeature.bindAllByeEvent coview_api.addEventListener(allbye)"
    );
    CHAT_SOCKET.emitCollaborationFinishMessage();
    if (deviceInfo.isAndroid()) {
      android.setExitHostAlert();
    }
    if (globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT) {
      NativeBridgeDelegate.exitMeetingRoom();
    }
    if (globalUserInfo.isInvited()) {
      NativeBridgeDelegate.openCommunicationHome();
    } else {
      NativeBridgeDelegate.joinRoom(roomInfo.roomID, roomInfo.roomName);
    }
    // TODO: peacekim:: check not to need this method for android
    if (deviceInfo.isiOS()) {
      NativeBridgeDelegate.showExitHostAlert();
      return;
    }
    CollaborationUI.hideLoadingIndicator();
  });
};

CoviewBridge.bindGuestByeEvent = function () {
  console.log("peacekim:: CollaborationFeature.bindGuestByeEvent");
  coview_api.addEventListener("guestbye", function () {
    console.log(
      "peacekim:: CollaborationFeature.bindGuestByeEvent coview_api.addEventListener(guestbye)"
    );
    CollaborationUI.hideLoadingIndicator();
  });
};

CoviewBridge.bindDestroyEvent = function () {
  console.log("peacekim:: CollaborationFeature.bindDestroyEvent");
  coview_api.addEventListener("destroy", function () {
    console.log(
      "peacekim:: CollaborationFeature.bindDestroyEvent coview_api.addEventListener(destroy)"
    );
    CHAT_SOCKET.emitCollaborationFinishMessage();
    alert(getLocalizedString("inform_exit_host_collaboration"));
    CoviewBridge.exitCollaboration();
    CollaborationUI.hideLoadingIndicator();
  });
};

CoviewBridge.bindMessageEvent = function () {
  console.log("peacekim:: CollaborationFeature.bindMessageEvent");
  coview_api.addEventListener("message", async function (event, json) {
    console.log(
      "peacekim:: CollaborationFeature.bindMessageEvent coview_api.addEventListener(message), api: " +
        json.api
    );
    if (globalUserInfo.isLeaved) {
      return;
    }
    switch (json.api) {
      case "LoginResponse":
        CollaborationFeature.didReceiveLoginResponseMessage();
        break;
      case "CreateRoomResponse":
        if (json.resultCode == 200) {
          CollaborationFeature.didReceiveCreateRoomResponseMessage();
          CollaborationFeature.checkAndRetryCamera();
        }
        break;
      case "joinRoomInfoResponse":
        if (json.resultCode != 200) {
          CollaborationFeature.didReceivedJoinRoomInfoResponseMessage();
        }
        break;
      case "JoinRoomResponse":
        if (json.resultCode != 200) {
          break;
        }
        console.log("peacekim:: will call CollaborationFeature.updateHost 1");
        CollaborationFeature.updateHost();
      // fall through
      case "RoomMemberJoinedEvent":
      // fall through
      case "RoomMemberLeavedEvent":
        attendingUsers = new Array();
        for (let key in g_participants) {
          attendingUsers.push(key);
        }
        CollaborationUI.refreshJoinedCollaboration(attendingUsers);
        break;
      case "HostRequest":
        // to be called by
        // wc_api.dispatchEvent (new Event ("message"), {"HostRequest":"userID"});
        break;
      case "fileChange":
        if (globalUserInfo.collaborationType != COLLABORATION_TYPE.CAMERA) {
          break;
        }
        LoadMobileShareFile(json.fileName);
        backgroundFileName = json.fileName;
        break;
      case "ReceiveMediaResponse":
        if (isBoard && g_isMainMan) {
          wc_api.dispatchEvent(new Event("message"), {
            api: "fileChange",
            fileName: backgroundFileName,
          });
        }
        break;
      case "IceCandidateEvent": // do nothing for ice condidate event
        break;
      case "HeartbeatResponse": // do nothing for heartbeat response
        break;
      default:
        console.debug("Unrecognized api", json);
        break;
    }
  });
};

CollaborationFeature.didReceiveLoginResponseMessage = async function () {
  const isDocument =
    globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT;
  const isAttendee =
    globalUserInfo.joinType == COLLABORATION_JOIN_TYPE.ATTENDEE;
  const isHost = globalUserInfo.joinType == COLLABORATION_JOIN_TYPE.HOST;

  console.log(
    "peacekim:: CollaborationFeature.didReceiveLoginResponseMessage isDocument : " +
      isDocument +
      ", isAttendee: " +
      isAttendee +
      ", isHost: " +
      isHost
  );

  if (isDocument) {
    if (isAttendee) {
      NativeBridgeDelegate.startContentView();
    } else if (isHost) {
      globalUserInfo.meetingID = NativeBridgeDataSource.createContentView();
      if (globalUserInfo.meetingID == "-1") {
        //会議室作成失敗
        CoviewBridge.finishCollaboration();
        return;
      }
    }
  }

  switch (globalUserInfo.joinType) {
    case COLLABORATION_JOIN_TYPE.INVITED:
    // fall through
    case COLLABORATION_JOIN_TYPE.ATTENDEE:
      // TODO:: here to update host
      coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);

      break;
    case COLLABORATION_JOIN_TYPE.HOST:
      let deleteRoomResult = JSON.parse(
        await deleteRoom(globalUserInfo.roomId)
      );
      if (deleteRoomResult.resultCode == 200) {
        waitMillisecond(3000);
      }
      coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
      break;
    default:
      break;
  }
  console.log("peacekim:: will call CollaborationFeature.updateHost 3");
  CollaborationFeature.updateHost();
  CollaborationUI.moveToVideoShareArea();
};

CollaborationFeature.didReceiveCreateRoomResponseMessage = function () {
  console.log(
    "peacekim:: CollaborationFeature.didReceiveCreateRoomResponseMessage"
  );
  let coviewInviteMessage =
    "" +
    messageSeperator +
    MessageType.COMMUNICATIONSTART +
    messageSeperator +
    CHAT_UTIL.getCollaborationTypeNumber(globalUserInfo.collaborationType);

  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT) {
    coviewInviteMessage += messageSeperator + globalUserInfo.meetingID;
  }

  CHAT_SOCKET.emitCreateMessage(coviewInviteMessage, 0);
};

CollaborationFeature.didReceivedJoinRoomInfoResponseMessage = function () {
  console.log(
    "peacekim:: CollaborationFeature.didReceivedJoinRoomInfoResponseMessage"
  );
  alert(getLocalizedString("not_exist_sharing_call"));
  coview_api.LeaveRoom();
  $(".coview_share_area").hide();
  CollaborationUI.hideLoadingIndicator();
  NativeBridgeDelegate.joinRoom(roomInfo.roomID, roomInfo.roomName);
};

CoviewBridge.changeHost = function (userID) {
  console.log("peacekim:: CoviewBridge.changeHost userID: " + userID);
  // call in agent_app.js
  coview_api.HostChange(userID);
};

CoviewBridge.addLoginID = function (loginID) {
  console.log("peacekim:: CoviewBridge.addLoginID loginID: " + loginID);
  const url = BIZ_TASK_YELL_URL + "/auth/getuser";
  $.ajax({
    url: url,
    method: "post",
    data: {
      id: loginID,
    },
    success: function (result) {
      if (result.statusCode != 200) {
        coview_api.addUser(loginID);
      }
    },
    error: function (err) {
      console.error(err.toString());
    },
  });
};

CollaborationFeature.updateHost = function () {
  console.log(
    "peacekim:: CollaborationFeature.updateHost g_isMainMan: " +
      g_isMainMan +
      ", g_isMainManUsername: " +
      g_isMainManUsername +
      ", g_username: " +
      g_username
  );

  if (g_isMainMan) {
    CollaborationUI.showHostButtons();
  } else {
    CollaborationUI.hideHostButtons();
  }

  CollaborationUI.showHostMark(g_isMainManUsername);

  $("#remoteVideoNameSpan").addClass("hide");
};

CollaborationUI.showHostButtons = function () {
  console.log("peacekim:: CollaborationUI.showHostButtons");
  $(".host_contents").removeClass("none");
  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.CAMERA) {
    $(".photo_select_button").removeClass("none");
  }
  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.VIDEO) {
    $(".video_contents_host").removeClass("none");
    $(".video_contents_user").addClass("none");
  }
};

CollaborationUI.hideHostButtons = function () {
  console.log("peacekim:: CollaborationUI.hideHostButtons");
  $(".host_contents").addClass("none");
  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.CAMERA) {
    $(".photo_select_button").addClass("none");
  }
  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.VIDEO) {
    $(".video_contents_user").removeClass("none");
    $(".video_contents_host").addClass("none");
  }
};

CollaborationUI.showHostMark = function (hostName) {
  console.log("peacekim:: CollaborationUI.showHostMark hostName: " + hostName);

  // remove all host mark
  attendingUsers.forEach(function (userName) {
    const user = "#collaboration_user_" + getReplacedLoginId(userName);
    $(user).removeClass("host");
  });

  // set host name as current user if host name is not set
  if (hostName == "") {
    hostName = getReplacedLoginId(globalUserInfo.loginId);
  }

  // find host named div
  const hostUserDiv = $("#collaboration_user_" + getReplacedLoginId(hostName));

  // add host mark
  if (!hostUserDiv.hasClass("host")) {
    hostUserDiv.addClass("host");
  }
};

function captureAndShareImage(urls, changeHostName) {
  console.log("peacekim:: share-event-listener.js captureAndShareImage");
  addCaptureEffect();
  $(this).removeClass("on");
  var w, h;
  const video = document.getElementById("localVideo");
  const canvas = document.createElement("canvas");
  if (clientOrientaionState == 1) {
    canvas.width = w = 680;
    canvas.height = h = 515;
  } else {
    canvas.width = w = 386;
    canvas.height = h = 515;
  }
  if (canvas.getContext) {
    const ctx = canvas.getContext("2d");
    ctx.drawImage(video, 0, 0, w, h);
    ctx.drawImage(document.getElementById("canvasRemote"), 0, 0, w, h);
  }

  canvas.toBlob(function (blob) {
    canvasRemote.style.backgroundImage =
      "url('" + URL.createObjectURL(blob) + "')";

    canvasRemote.style.backgroundSize = "contain";

    $(canvasRemote).attr(
      "height",
      $(snapshots[cpatureViewIndex]).attr("height")
    );

    $(canvasRemote).attr("width", $(snapshots[cpatureViewIndex]).attr("width"));

    CollaborationUI.configureCanvasSize($(canvas));

    $(".canvas_wrap").css("background-color", "#000");
    $(".clear_img").show();
    SetShareMenuState("on");
    WithImageShareBtnState("on");

    //Fermi側にイメージ保存。
    let formData = new FormData();
    const uploadFileName =
      "capture_share_" + g_webroom + "_" + g_shareCount + ".png";
    g_shareCount++;
    formData.append("imgFile", blob, uploadFileName);

    $.ajax({
      type: "post",
      url: g_coviewapiserverADDR + "/upload/create",
      data: formData,
      processData: false,
      contentType: false,
      success: function (res) {
        setTimeout(function () {
          SendFileShare(uploadFileName);
          $("#coviewCaptureCtrBtn").hide();
          $("#coviewRecCtrBtn").hide();
          $(".coview_on_media_btn_back").show();
          //アーカイブ保存。
          ArchiveFileManage(blob, uploadFileName, urls);
        }, 1500);
      },
      error: function (err) {
        console.error(err);
      },
    });
  });
}

CollaborationUI.configureCanvasSize = function (canvas) {
  console.log("peacekim:: CollaborationUI.configureCanvasSize");
  const canvasWrap = $(".canvas_wrap");
  const canvasWidth = $(canvas).attr("width");
  const canvasHeight = $(canvas).attr("height");
  const canvasRatio = canvasWidth / canvasHeight;
  const reversedCanvasRatio = canvasHeight / canvasWidth;
  const canvasWidthValue = canvasWrap.css("width").replace("px", "");
  const canvasHeightValue = canvasWrap.css("height").replace("px", "");
  let h;
  let w;
  if (canvasWidthValue / canvasHeightValue < canvasRatio) {
    h = canvasWidthValue * reversedCanvasRatio;
    w = canvasWidthValue;
  } else {
    h = canvasHeightValue;
    w = canvasHeightValue / reversedCanvasRatio;
  }
  $(canvasRemote).css("height", h);
  $(canvasRemote).css("width", w);
  $(canvasRemote).css("margin-top", -h / 2);
  $(canvasRemote).css("margin-left", -w / 2);
};

function getReplacedLoginId(loginId) {
  console.log(
    "peacekim:: share-event-listener.js getReplacedLoginId loginID: " + loginId
  );
  return loginId.replaceAll(globalUserInfo.shopName + "_", "");
}

CoviewBridge.exitCollaboration = function () {
  console.log(
    "peacekim:: CoviewBridge.exitCollaboration g_isMainMan: " + g_isMainMan
  );
  CollaborationFeature.disableScrollLock();
  Common.showLoadingIndicator();

  if (g_isMainMan) {
    CHAT_SOCKET.emitCollaborationFinishMessage();
  }
  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT) {
    NativeBridgeDelegate.exitMeetingRoom();
  }

  if ($("#recordBtn .record").hasClass("disable")) {
    recordStop(CoviewBridge.finishCollaboration);
  } else {
    CoviewBridge.finishCollaboration();
  }
};

CoviewBridge.finishCollaboration = function () {
  console.log("peacekim:: CoviewBridge.finishCollaboration");
  Common.showLoadingIndicator();
  coview_api.LeaveRoom();
  if (coview_api.getRoomUsers()) {
    NativeBridgeDelegate.finishCollaboration();
  }
  globalUserInfo.isLeaved = true;

  if (globalUserInfo.isInvited()) {
    NativeBridgeDelegate.openCommunicationHome();
  } else {
    NativeBridgeDelegate.joinRoom(roomInfo.roomID, roomInfo.roomName);
  }
  Common.dismissLoadingIndicator();
};

// Display User List
CollaborationUI.refreshJoinedCollaboration = function (loginIDList) {
  console.log(
    "peacekim:: CollaborationUI.refreshJoinedCollaboration loginIDList: " +
      loginIDList
  );
  for (var count = 0; count < loginIDList.length; count++) {
    loginIDList[count] = loginIDList[count].replaceAll(
      globalUserInfo.shopName + "_",
      ""
    );
  }

  $("#collaboration_overlay_user_list").html("");

  const joinedUserListTemplate = getTemplate(
    TemplateURL.COLLABORATION_OVERLAY_USER_LIST
  );

  const joinedUserList =
    NativeBridgeDataSource.getUserListByLoginId(loginIDList);
  const sortedUserList = new Array();

  loginIDList.forEach(function (userID) {
    joinedUserList.forEach(function (user) {
      if (userID == user.loginId) {
        sortedUserList.push(user);
      }
    });
  });

  sortedUserList.forEach(function (user) {
    user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
  });

  let html = Mustache.render(joinedUserListTemplate, {
    joinedUserList: sortedUserList,
  });

  let obj = jQuery.parseHTML(html);
  $("#collaboration_overlay_user_list").append(obj);

  CollaborationFeature.updateHost();
};

CollaborationUI.moveToVideoShareArea = function () {
  console.log("peacekim:: CollaborationUI.moveToVideoShareArea");
  CollaborationUI.showLoadingIndicator();
  $(".coview_share_area").show();
  $("#collabo_main").removeClass("none");
};
