var FermiWebSocketMessageHandler = {};

FermiWebSocketMessageHandler.bindWebSocketMessage = function () {
  fw.socket.on("message", async function (data) {
    if (g_isMainMan) {
      // 自分がホストの場合
      FermiWebSocketMessageHandler.handleMessagesToHost(data);
    } else if (data.payload.loginId == globalUserInfo.loginId) {
      // 自分自身の場合
      FermiWebSocketMessageHandler.handleMessagesToSelf(data);
    }
    // global messages
    FermiWebSocketMessageHandler.handleMessagesToAll(data);
  });
};

FermiWebSocketMessageHandler.handleMessagesToHost = function (data) {
  // HOSTの場合
  switch (data.type) {
    case "CAPTURE_REQUEST":
      FermiWebSocketMessageHandler.captureRequest(data);
      break;
    case "HOST_CHANGE_RESPONSE":
      FermiWebSocketMessageHandler.hostChangeResponse(data);
      break;
    case "GET_COLLABORATION_TYPE":
      FermiWebSocketMessageHandler.getCollaborationType(data);
      break;
    case "SHARE_FILE_HOST":
      if (globalUserInfo.collaborationType != COLLABORATION_TYPE.CAMERA) {
        FermiWebSocketMessageHandler.shareFileHost();
      }
      break;
    case "CHANGE_HOST_APPLY":
      FermiWebSocketMessageHandler.changeHostApplyForHost(data);
      break;
    default:
      break;
  }
};

FermiWebSocketMessageHandler.handleMessagesToSelf = function (data) {
  // 自分自身の場合
  switch (data.type) {
    case "HOST_CHANGE_REQUEST":
      FermiWebSocketMessageHandler.hostChangeRequest(data);
      break;
    case "PIP_END_REQUEST":
      if (globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT) {
        FermiWebSocketMessageHandler.pipEndRequest();
      }
      break;
    case "GET_COLLABORATION_TYPE_RESPONSE":
      FermiWebSocketMessageHandler.getCollaborationTypeResponse(data);
      break;
    default:
      break;
  }
};

FermiWebSocketMessageHandler.handleMessagesToAll = function (data) {
  switch (data.type) {
    case "CHANGE_COLLABORATION":
      FermiWebSocketMessageHandler.changeCollaboration(data);
      break;
    case "SHARE_FILE":
      if (globalUserInfo.collaborationType != COLLABORATION_TYPE.CAMERA) {
        FermiWebSocketMessageHandler.shareFile();
      } else {
        FermiWebSocketBridge.shareFileHost(COLLABORATION_TYPE.CAMERA);
      }
      break;
    case "API_SEND_OWNER_CHANGE_COMPLETE":
      FermiWebSocketMessageHandler.apiSendOwnerChangeComplete(data);
      CollaborationFeature.updateHost();
      FermiWebSocketBridge.hostUpdated();
      FermiWebSocketMessageHandler.hostRequestDone();
      break;
    case "API_SEND_OWNER_CHANGE_CONFIRM":
      if (globalUserInfo.collaborationType == COLLABORATION_TYPE.CAMERA) {
        FermiWebSocketMessageHandler.apiSendOwnerChangeConfirm();
      }
      break;
    case "CHANGE_HOST_APPLY":
      FermiWebSocketMessageHandler.changeHostApplyForNotHost(data);
      break;
    case "HOST_REQUEST_DONE":
      FermiWebSocketMessageHandler.hostRequestDone();
      CollaborationFeature.updateHost();
      break;
    case "HOST_REQUEST_REJECT":
      FermiWebSocketMessageHandler.hostRequestReject(data);
      break;
    case "API_WELCOME":
      if (globalUserInfo.joinType != COLLABORATION_JOIN_TYPE.INVITED) {
        FermiWebSocketMessageHandler.apiWelcome();
      } else {
        // when collaboration type is invited it should be dm room also
        roomInfo.roomType = ChatRoomType.DM;
        FermiWebSocketBridge.getCollaborationType();
      }
      CollaborationFeature.updateHost();
      break;
    case "SWITCH_VIDEO":
      CollaborationFeature.updateHost();
      CollaborationUI.userListSlideOut();
      $(".profile_favorite_btn").click();
      break;
    case "HOST_UPDATED":
      CollaborationFeature.updateHost();
      break;
    default:
      break;
  }
};

// CHANGE_COLLABORATION
FermiWebSocketMessageHandler.changeCollaboration = function (data) {
  const newMeetingID = data.payload.newMeetingId;
  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT) {
    NativeBridgeDelegate.exitMeetingRoom();
    NativeBridgeDelegate.finishPIPMode(true);

    if (deviceInfo.isAndroid()) {
      $(".pip_indicator").addClass("none");
    }

    waitMillisecond(500);
    updateCanvasSize();
  }

  FermiWebSocketMessageHandler.updateJoinChangeCollaboration(
    data.payload.collaborationType
  );

  globalUserInfo.meetingID = newMeetingID;

  CollaborationUI.updateScreen(globalUserInfo.collaborationType);

  NativeBridgeDelegate.joinChangedCollaboration(
    globalUserInfo.collaborationType,
    newMeetingID
  );

  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT) {
    NativeBridgeDelegate.joinMeetingRoom(newMeetingID);
  }
};

// SHARE_FILE
FermiWebSocketMessageHandler.shareFile = function () {
  CollaborationUI.updateScreen(COLLABORATION_TYPE.CAMERA);
  globalUserInfo.collaborationType = COLLABORATION_TYPE.CAMERA;
  FermiWebSocketBridge.shareFileHost(COLLABORATION_TYPE.CAMERA);
  CollaborationFeature.updateHost();
};

// SHARE_FILE_HOST
FermiWebSocketMessageHandler.shareFileHost = function () {
  CollaborationUI.updateScreen(COLLABORATION_TYPE.CAMERA);
  globalUserInfo.collaborationType = COLLABORATION_TYPE.CAMERA;
  CollaborationFeature.updateHost();
};

// CAPTURE_REQUEST
FermiWebSocketMessageHandler.captureRequest = function (data) {
  const name = data.payload.name;
  if (confirm(name + getLocalizedString("request_capture")) == false) {
    return;
  }

  if ($("#recordBtn .record").hasClass("disable")) {
    screenLock();
    recordStop().then(function () {
      $("#screenLock").remove();
      captureAndShareImage(
        serverInfo.cmsURL + "/chatapi/file/uploadArchive",
        name
      );
    });
  } else {
    captureAndShareImage(
      serverInfo.cmsURL + "/chatapi/file/uploadArchive",
      name
    );
  }
};

// HOST_CHANGE_REQUEST
FermiWebSocketMessageHandler.hostChangeRequest = function (data) {
  FermiWebSocketBridge.hostChangeResponse(data);
};

// HOST_CHANGE_RESPONSE
FermiWebSocketMessageHandler.hostChangeResponse = function (data) {
  const isAndroid = data.payload.isAndroid;
  const isAble = data.payload.isAble;
  if (
    isAndroid &&
    !isAble &&
    globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT
  ) {
    coview_api.HeartBeatUser(globalUserInfo.loginId);
    // 対象ユーザの端末バージョンでは文書協業が利用できません。
    alert(getLocalizedString("err_target_android_version_not_support"));
  } else {
    FermiWebSocketBridge.pipEndRequest(data.payload.loginId);
    waitMillisecond(500);
    CoviewBridge.changeHost(data.payload.loginId);
  }
};

// PIP_END_REQUEST
FermiWebSocketMessageHandler.pipEndRequest = function () {
  NativeBridgeDelegate.finishPIPMode(true);
  if (deviceInfo.isAndroid()) {
    $(".pip_indicator").addClass("none");
  }
};

// API_SEND_OWNER_CHANGE_COMPLETE
FermiWebSocketMessageHandler.apiSendOwnerChangeComplete = function (data) {
  penOff();
  if ($("#recordBtn .record").hasClass("disable")) {
    recordStop();
  }
  if ($("#micBtn .voice").hasClass("disable")) {
    micOff();
  } else {
    micOn();
  }
};

// API_SEND_OWNER_CHANGE_CONFIRM
FermiWebSocketMessageHandler.apiSendOwnerChangeConfirm = function () {
  waitMillisecond(500);
  removeOldLocalVideo(g_localStream);
};

// CHANGE_HOST_APPLY
FermiWebSocketMessageHandler.changeHostApplyForNotHost = function (data) {
  NativeBridgeDelegate.setHostRequestFlg(HostRequestFlag.DOING);
  waitMillisecond(500);
};

// CHANGE_HOST_APPLY
FermiWebSocketMessageHandler.changeHostApplyForHost = function (data) {
  const hostID = data.payload.hostId;
  coview_api.HeartBeatUser(globalUserInfo.loginId);
  NativeBridgeDelegate.finishPIPMode(true);
  if (deviceInfo.isAndroid()) {
    $(".pip_indicator").addClass("none");
  }

  NativeBridgeDelegate.setHostRequestFlg(HostRequestFlag.DOING);
  //PIPモード終了時に0.5秒のアニメーションの影響で画面崩れ発生問題対応で、0.5秒後にアラート表示
  setTimeout(function () {
    if (confirm(getLocalizedString("norify_request_host_change", hostID))) {
      CoviewBridge.changeHost(hostID);
      NativeBridgeDelegate.setHostRequestFlg(HostRequestFlag.DONE);
    } else {
      FermiWebSocketBridge.hostRequestReject(hostID);
      //上の実行した後、「CHANGE_HOST_APPLY」が受信され、ステータスが「DOING」になるので1秒後に実行
      setTimeout(function () {
        NativeBridgeDelegate.setHostRequestFlg(HostRequestFlag.DONE);
      }, 1000);
    }
    FermiWebSocketBridge.hostRequestDone(hostID);
  }, 500);
};

// HOST_REQUEST_DONE
FermiWebSocketMessageHandler.hostRequestDone = function () {
  NativeBridgeDelegate.setHostRequestFlg(HostRequestFlag.DONE);
};

// HOST_REQUEST_REJECT
FermiWebSocketMessageHandler.hostRequestReject = function (data) {
  if (data.payload.hostId == globalUserInfo.loginId) {
    alert("REJECT for owner user");
  }
  NativeBridgeDelegate.setHostRequestFlg(HostRequestFlag.DONE);
};

// GET_COLLABORATION_TYPE
FermiWebSocketMessageHandler.getCollaborationType = function (data) {
  FermiWebSocketBridge.getCollaborationTypeResponse(data.payload.loginId);
};

// GET_COLLABORATION_TYPE_RESPONSE
FermiWebSocketMessageHandler.getCollaborationTypeResponse = function (data) {
  const collaborationType = data.payload.collaborationType;
  const meetingID = data.payload.newMeetingId ?? 0;

  FermiWebSocketMessageHandler.updateJoinChangeCollaboration(collaborationType);
  globalUserInfo.meetingID = meetingID;
  CollaborationUI.updateScreen(globalUserInfo.collaborationType);

  NativeBridgeDelegate.joinChangedCollaboration(
    globalUserInfo.collaborationType,
    meetingID
  );

  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT) {
    NativeBridgeDelegate.joinMeetingRoom(meetingID);
  }
};

// API_WELCOME
FermiWebSocketMessageHandler.apiWelcome = function () {
  FermiWebSocketBridge.getCollaborationType();
  globalUserInfo.joinType = COLLABORATION_JOIN_TYPE.ATTENDEE;
};

FermiWebSocketMessageHandler.updateJoinChangeCollaboration = function (
  collaborationType
) {
  if (
    deviceInfo.isAndroid() &&
    collaborationType == COLLABORATION_TYPE.DOCUMENT &&
    deviceInfo.androidVersion < ANDROID_SDK_VERSION.O
  ) {
    coview_api.HeartBeatUser(globalUserInfo.loginId);
    alert(getLocalizedString("not_support_version"));
    globalUserInfo.collaborationType = COLLABORATION_TYPE.CAMERA;
  } else {
    globalUserInfo.collaborationType = collaborationType;
  }
};
