/* --------------------------------------------------- */
/* Functions                                           */
/* --------------------------------------------------- */
let coview_api = new CoviewApi();
var isDocument = false;
var isBoard = false;
let isLeaved = false;
let timeInterval = null;
var backgroundFileName;

$(function () {
  var coviewApiActive = coview_api.Init({
    testSTRParam: "param1",
    testNUMParam: 77,
    testBOOLParam: false,
    coview_api_srv_addr: "https://biztaskyell.abookcloud.com",
    coview_wrap_id: "coviewShare",
    coview_api_key: "8dda7092c5820d663",
  });

  // special button IN Chat ui
  $("#coviewShareMainBtn").on("click", function (e) {
    e.stopPropagation();
    if ($(".coview_share_dropdown_bar").is(":visible") == true) {
      Coview_shareDropdownHide();

      if ($(".coview_share_photo_select_bubble").is(":visible") == true) {
        $(".coview_share_photo_select_bubble").slideUp();
      }
    } else {
      $(".coview_share_dropdown_bar").slideDown();
    }
  });

  $("#coviewShareCloseButton").on("click", function (e) {
    coview_api.LeaveRoom();
    $(".coview_share_area").hide();
  });

  $("body").on("click", function () {
    Coview_shareDropdownHide();

    if ($(".coview_share_photo_select_bubble").is(":visible") == true) {
      $(".coview_share_photo_select_bubble").slideUp();
    } else {
      $(".coview_share_dropdown_bar").slideDown();
    }
  });

  $(document).on("click", ".coview_share_request", function () {
    console.log("globalUserInfo", globalUserInfo);
    if ($(this).hasClass(collaborationTypeKey.VIDEO) == true) {
      globalUserInfo.coWorkType = collaborationTypeKey.VIDEO;
      $(".coview_share_title_name").text("LIVE");
    } else if ($(this).hasClass(collaborationTypeKey.CAMERA) == true) {
      globalUserInfo.coWorkType = collaborationTypeKey.CAMERA;
      $(".coview_share_title_name").text("ライブラリ");
    } else if ($(this).hasClass(collaborationTypeKey.AUDIO) == true) {
      globalUserInfo.coWorkType = collaborationTypeKey.AUDIO;
      $(".coview_share_title_name").text("音声通話");
    }

    coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();
  });

  /* --------------------------------------------------- */
  /* Video, photo, chat, doc                             */
  /* --------------------------------------------------- */
  $("#coviewShareChat").on("click", function () {
    console.log("ON click coviewShareChat");
  });

  $("#coviewSharePhoto").on("click", function (e) {
    e.stopPropagation();
    console.log("ON click coviewSharePhoto");

    if ($(".coview_share_photo_select_bubble").is(":visible") == true) {
      $(".coview_share_photo_select_bubble").slideUp();
    } else {
      $(".coview_share_photo_select_bubble").slideDown();
    }
  });

  $("#coviewSharePhotoCamera").on("click", function () {
    $(".coview_share_photo_select_bubble").hide();
    globalUserInfo.coWorkType = collaborationTypeKey.CAMERA;
    coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();

    $(".coview_share_title_name").text("カメラ");
  });
  $("#coviewSharePhotoGallery").on("click", function () {
    $(".coview_share_photo_select_bubble").hide();
    globalUserInfo.coWorkType = "gallery";
    coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();

    $(".coview_share_title_name").text("ライブラリ");
  });

  $("#coviewShareAudio").on("click", function () {
    Coview_connect_audio_collaboration();
  });

  $("#coviewShareLive").on("click", function () {
    console.log("ON click coviewShareLive");
    globalUserInfo.coWorkType = "video";
    console.log("globalUserInfo", globalUserInfo);

    coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();

    $(".coview_share_title_name").text("LIVE");
  });

  coview_api.addEventListener("ready", function () {
    console.log("=============> READY : ready for coview api");
    Coview_addLoginId(globalUserInfo.loginId);
    coview_api.Login(globalUserInfo.loginId);
  });

  coview_api.addEventListener("start", function () {
    console.log("=============> START : share start");
    $("#loadingIndicator").removeClass("full_active");
  });

  coview_api.addEventListener("allbye", function () {
    console.log("=============> ALL BYE : share allbye");
    $("#loadingIndicator").removeClass("full_active");
  });

  coview_api.addEventListener("guestbye", function () {
    console.log("=============> GUEST BYE : share guestbye");
    $("#loadingIndicator").removeClass("full_active");
  });

  coview_api.addEventListener("hostbye", function () {
    console.log("=============> HOST BYE : share hostbye");
    alert(getLocalizedString("inform_exit_host_collaboration"));
    Coview_exitCollaboration();
    $("#loadingIndicator").removeClass("full_active");
  });

  coview_api.addEventListener("destroy", function () {
    console.log("=============> DESTROY : share destroy");
    coview_api.LeaveRoom();
    $(".coview_share_area").hide();
    $("#loadingIndicator").removeClass("full_active");
  });
    
  var meetingId;
    
  coview_api.addEventListener("message", async function (event, json) {
    console.log("+++ addEventListener", json);
    console.log("processMessage api = ", json.api);
    if (isLeaved) return;
    let loginIdList = new Array();
    switch (json.api) {
      case "LoginResponse":
        if (globalUserInfo.coWorkType == collaborationTypeKey.DOCUMENT) {
          isDocument = true;
          globalUserInfo.coWorkType = collaborationTypeKey.AUDIO;
        }
        if (globalUserInfo.coWorkType == collaborationTypeKey.BOARD) {
          isBoard = true;
          globalUserInfo.coWorkType = collaborationTypeKey.CAMERA;
        }
        hostSearchInterval();
        if (collaborationJoinFlg == "1") {
          coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
          if (isDocument) {
            if (CHAT_UTIL.isIOS()) {
                webkit.messageHandlers.startContentView.postMessage({});
            } else if (CHAT_UTIL.isAndroid()) {
              android.startContentView();
            }
          }
        } else if (collaborationJoinFlg == "0") {
          coview_api.CreateRoom(
            globalUserInfo.roomId,
            globalUserInfo.coWorkType
          );
          if (isDocument) {
            if (CHAT_UTIL.isIOS()) {
              meetingId = CHAT_DB.createContentView();
            } else if (CHAT_UTIL.isAndroid()) {
              meetingId = android.createContentView();
            }
          }
        } else if (collaborationJoinFlg == "2") {
          coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
        }
        Coview_moveToVideoShareArea();

        break;
      case "CreateRoomResponse":
        if (json.resultCode == 200) {
          var coviewInviteMessage;
          if (isDocument) {
            coviewInviteMessage =
              "" +
              messageSeperator +
              messageType.COMMUNICATIONSTART +
              messageSeperator +
              CHAT_UTIL.getCollaborationType(collaborationTypeKey.DOCUMENT) +
              messageSeperator +
              meetingId;
          } else if (isBoard) {
            coviewInviteMessage =
              "" +
              messageSeperator +
              messageType.COMMUNICATIONSTART +
              messageSeperator +
              collaborationType.BOARD;
          } else {
            coviewInviteMessage =
              "" +
              messageSeperator +
              messageType.COMMUNICATIONSTART +
              messageSeperator +
              CHAT_UTIL.getCollaborationType(globalUserInfo.coWorkType);
          }
          socket.emit(
            "createMessage",
            {
              text: coviewInviteMessage,
            },
            0
          );
          if (isBoard) {
            $('#open_file_upload').on("click",function(e){
                e.preventDefault();
            });
          }
        } else {
        }
        break;
      case "JoinRoomInfoResponse":
        if (json.resultCode == 200) {
        } else {
          alert(
            "Not exist sharing call (" +
              json.resultCode +
              ")\nPlease using share menu."
          );
          coview_api.LeaveRoom();
          $(".coview_share_area").hide();
          $("#loadingIndicator").removeClass("full_active");
        }
        break;
      case "JoinRoomResponse":
        if (json.resultCode == 200) {
          hostSearchInterval();
          for (let key in g_participants) {
            loginIdList.push(key);
          }
          CHAT_UI.refreshJoinedCollaboration(loginIdList);
        } else {
        }
        break;
      case "RoomMemberJoinedEvent":
        for (let key in g_participants) {
          loginIdList.push(key);
        }
        CHAT_UI.refreshJoinedCollaboration(loginIdList);
        break;
      case "RoomMemberLeavedEvent":
        for (let key in g_participants) {
          loginIdList.push(key);
        }
        CHAT_UI.refreshJoinedCollaboration(loginIdList);
        break;
      case "HostRequest":
        // to be called by
        // wc_api.dispatchEvent (new Event ("message"), {"HostRequest":"userID"});
        console.log("consoleLog", json);
        break;
      case "fileChange":
        LoadMobileShareFile(json.fileName);
        backgroundFileName = json.fileName;
        console.log("fileChange", json);
        break;
      case "ReceiveMediaResponse":
        if (isBoard && g_isMainMan) {
          wc_api.dispatchEvent (new Event ("message"), {"api":"fileChange","fileName":backgroundFileName});
        }
        break;
      default:
        console.log("Unrecognized api", json);
        break;
    }
  });
});

function Coview_shareDropdownHide() {
  $(".coview_share_dropdown_bar").slideUp();
  $(".coview_share_photo_select_bubble").slideUp();
}

function Coview_moveToVideoShareArea() {
  $("#loadingIndicator").addClass("full_active");
  $(".coview_share_area").show();
  $("#collabo_main").removeClass("none");
}

function changeCollaboration(changeCollaborationType) {
  switch (changeCollaborationType) {
    case collaborationType.AUDIO:
      coview_api.ChangeCollaboration('audio');
      break;
    case collaborationType.CAMERA:
      coview_api.ChangeCollaboration('image');
      break;
    case collaborationType.VIDEO:
      coview_api.ChangeCollaboration('video');
      break;
    case collaborationType.DOCUMENT:
      coview_api.ChangeCollaboration('audio');
      break;
    case collaborationType.BOARD:
      coview_api.ChangeCollaboration('audio');
      break;
  }
  var collaborationChangeMessage = dataMessageScheme + messageSeperator + collaborationChangeMessage;
  socket.emit("createMessage", {text: collaborationChangeMessage}, 0);
  changeCollaborationType

  if (CHAT_UTIL.isIOS()) {
    //TODO Nativeに変換するCollaborationTypeを保存。
  } else if (CHAT_UTIL.isAndroid()) {
    android.setJoinCollaborationType(changeCollaborationType);
  }
  initCollaborationUI(changeCollaborationType);
}

function initCollaborationUI(changeCollaborationType){
  if ($('.user_btn').hasClass("hide")) {
    $('.user_btn').click();
  }
  $(".menu_btn").click();
  $("link[href='./css/collaboration_board.css']").remove();
  switch (changeCollaborationType) {
    case collaborationType.AUDIO:
      $('.collaboration_contents').addClass('none');
      $('.voice_contents').removeClass('none');
      $('.user_btn').click();
      break;
    case collaborationType.CAMERA:
      $('.collaboration_contents').addClass('none');
      $('.picture_contents').removeClass('none');
      break;
    case collaborationType.VIDEO:
      $('.collaboration_contents').addClass('none');
      $('.video_contents').removeClass('none');
      break;
    case collaborationType.DOCUMENT:
      $('.collaboration_contents').addClass('none');
      $('.document_contents').removeClass('none');
      $('.user_btn').click();
      break;
    case collaborationType.BOARD:
      $('.collaboration_contents').addClass('none');
      $('.board_contents').removeClass('none');
      $('head').append('<link rel="stylesheet" href="./css/collaboration_board.css">');
      break;
  }
}

function Coview_exitCollaboration(isDocument = false) {
  if (isDocument) {
    if (CHAT_UTIL.isIOS()) {
      webkit.messageHandlers.exitMeetingRoom.postMessage({});
    } else if (CHAT_UTIL.isAndroid()) {
      android.exitMeetingRoom();
    }
  }
  clearInterval(timeInterval);
  coview_api.LeaveRoom();
  if (coview_api.getRoomUsers()) { android.finishCollaboration() };
  isLeaved = true;
  if (collaborationJoinFlg != '2') {
    CHAT_UI.joinRoom(
      CHAT.globalLoginParameter.roomId,
      CHAT.globalLoginParameter.name
    );
  } else {
    if (typeof android != "undefined") {
      android.openCommunicationHome();
    } else {
      webkit.messageHandlers.openCommunicationHome.postMessage({});
    }
  }
}

function Coview_changeHost(userId) {
  console.log("Change Host To " + userId);
  changeOwnerSend(userId);
}

function Coview_addLoginId(loginId) {
  console.log("addUser loginId = " + loginId);
  var url = "https://biztaskyell.abookcloud.com/auth/getuser";
  $.ajax({
    url : url,
    method : 'post',
    data : {
      id : loginId
    },
    success : function (result) {
      console.log("result", result);
      if (result.statusCode != 200) {
        coview_api.addUser(loginId);
      }
    },
    error : function (err) {
      console.log(err.toString());
    }
  });
}

function Coview_connect_audio_collaboration() {
  globalUserInfo.coWorkType = collaborationTypeKey.AUDIO;
  coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
  Coview_moveToVideoShareArea();

  $(".coview_share_title_name").text("音声通話");
}

function hostSearchInterval() {
  let hostName = "";
  if (g_isMainMan) {
      $('.host_contents').removeClass('none');
      if (joinCollaborationType == collaborationType.CAMERA) {
          $('.photo_select_button').removeClass('none');
      }
  } else {
      $('.host_contents').addClass('none');
      if (joinCollaborationType == collaborationType.CAMERA) {
          $('.photo_select_button').addClass('none');
      }
  }
  function hostSearch() {
    if (hostName != g_isMainManUsername) {
      if (hostName != "") {
        $("#collaboration_user_" + hostName).removeClass("host");
      }
      $("#collaboration_user_" + g_isMainManUsername).addClass("host");
      hostName = g_isMainManUsername;
    } else {
      if (hostName == "") {
        if (!$("#collaboration_user_" + CHAT.globalLoginParameter.loginId).hasClass("host") && coview_api.getRoomUsers()) {
          $("#collaboration_user_" + CHAT.globalLoginParameter.loginId).addClass("host");
        }
      } else {
        if (!$("#collaboration_user_" + hostName).hasClass('host')) {
          $("#collaboration_user_" + hostName).addClass("host");
        }

      }
    }
  }
  timeInterval = setInterval(hostSearch, 3000);
}