var socket;

// 名前空間
var CHAT_SOCKET = {};

includeJs("./js/chat-websocket-message.js");
includeJs("./js/chat-websocket-refresh-group-list.js");
includeJs("./js/chat-websocket-refresh-user-list-in-group.js");

CHAT_SOCKET.socketCheck = function () {
  if (socket == null || socket.disconnected) {
    window.location.reload();
  }
};

CHAT_SOCKET.connectSocket = function () {
  if (IS_ONLINE == "true") {
    socket = io(CHAT_SERVER_URL);
    setSocketAction();
  } else {
    //オフラインの場合、DBからルーム一覧を表示。
    if (CHAT_UTIL.isIOS()) {
      //TODO IOSの場合
    } else if (CHAT_UTIL.isAndroid()) {
    }
  }
};

function setSocketAction() {
  /* ---------------------------------------------------
   * Socket Connect/Disconnect
   * --------------------------------------------------- */
  bindOnConnect();
  bindOnDisconnect();
  bindOnConnectError();

  /* ---------------------------------------------------
   * Chat Room List Tab
   * --------------------------------------------------- */
  bindOnNewMessage();
  bindOnNewNotification();
  bindOnRefreshGroupList();
  bindOnRefreshUserListInGroup();

  /* ---------------------------------------------------
  /* Show Error Log
  /* --------------------------------------------------- */
  bindOnShowServerError();
  bindOnRetryJoinProcess();
}

var bindOnConnect = function () {
  socket.on(SOCKET_KEY.CONNECT, function () {
    // socketが接続されたらチャット画面で画面を更新する
    $(".overlay").removeClass("active undismissable");
    // loadingIndicatorを表示
    CHAT_UI.showLoadingIndicator();
    requestLoginInfo();
    CHAT_UI.dismissLoadingIndicator();
  });
};

var requestLoginInfo = function () {
  // チャットルームに入場する際、sid, loginId, shopName, roomId, roomNameの情報を取得しNodeJsに渡す
  if (CHAT_UTIL.isIOS()) {
    webkit.messageHandlers.loginInfoRequestMessageHandlerId.postMessage({});
  } else if (CHAT_UTIL.isAndroid()) {
    android.getLoginParameter();
  }
};

var bindOnDisconnect = function () {
  socket.on(SOCKET_KEY.DISCONNECT, function () {
    //socketが切断されたら黒画面で画面を更新する
    $(".overlay").addClass("active undismissable");
    CHAT_UI.dismissLoadingIndicator();
  });
};

var bindOnConnectError = function () {
  socket.on(SOCKET_KEY.CONNECT_ERROR, function () {
    CHAT_UI.dismissLoadingIndicator();
  });
};

var bindOnNewNotification = function () {
  // Notification
  socket.on(SOCKET_KEY.NEW_NOTIFICATION, function (keyword, event) {
    const notificationString = getLocalizedString(event, keyword);
    $("#messageNotification")
      .finish()
      .text(notificationString)
      .delay(500)
      .slideDown()
      .delay(1500)
      .slideUp();
  });
};

var bindOnShowServerError = function () {
  socket.on(SOCKET_KEY.SHOW_SERVER_ERROR, function (message) {
    // #36215
    if (message.includes("SC_FORBIDDEN")) {
      alert("SC_FORBIDDEN");
      return;
    }

    if (message == "server error Ocurred") {
      message = getLocalizedString("serverErrorOccured");
    } else if (message == "Room not found") {
      message = getLocalizedString("errorRoomNotFound");
    }
    $("#customAlertTitle").text(message);
    $("#customAlertOk").text(getLocalizedString("yesTitle"));

    $("#customAlert")
      .appendTo("body")
      .modal({
        backdrop: "static",
        keyboard: false,
      })
      .on("click", "#customAlertOk", function (e) {});
    CHAT_UI.dismissLoadingIndicator();

    if (message == "Room not found") {
      CHAT.saveRoomInfo();
    }
  });
};

var bindOnRetryJoinProcess = function () {
  socket.on(SOCKET_KEY.RETRY_JOIN_PROCESS, function () {
    var ua = window.navigator.userAgent.toLowerCase();
    if (CHAT_UTIL.isIOS()) {
      webkit.messageHandlers.loginInfoRequestMessageHandlerId.postMessage({});
    } else if (CHAT_UTIL.isAndroid()) {
      android.getLoginParameter();
    } else {
      CHAT_UI.htmlElementTextInitialize("ko");
      // webでのsocket connect
      emitJoin();
    }
  });
};

var emitJoin = function () {
  socket.emit(SOCKET_KEY.JOIN, params, function (err) {
    if (err) {
      errorHandlingForEmitJoin();
      CHAT_UI.dismissLoadingIndicator();
      return;
    }

    updateRoomName(params.roomName);

    // loadingIndicatorを表示しない
    CHAT_UI.dismissLoadingIndicator();
  });
};

var errorHandlingForEmitJoin = function () {
  const positiveButton = $("#customAlertOk");
  // #36174
  $("#customAlertTitle").text(err);
  positiveButton.text(getLocalizedString("yesTitle"));

  $("#customAlert")
    .appendTo("body")
    .modal({
      backdrop: "static",
      keyboard: false,
    })
    .on("click", "#customAlertOk", function (e) {});
};

var updateRoomName = function (roomName) {
  const titleRoomName = $(".titleRoomName");
  if (roomName != undefined) {
    titleRoomName.text(roomName).data("roomName", roomName);
  } else {
    let roomListTitle = getLocalizedString("roomListTitle");
    titleRoomName.text(roomListTitle);
  }
};
