import GoEasy from "goeasy";

class GoEasyIM {
  constructor(options) {
    this.goeasy = null;
    this.id = options.id;
    this.data = options.data;
    this.host = options.host;
    this.appkey = options.appkey;
    this.modules = options.modules;
    this.create();
  }

  create() {
    this.goeasy = GoEasy.getInstance({
      host: this.host,
      appkey: this.appkey,
      modules: this.modules,
    });
    return this.goeasy;
  }

  async connect() {
    await new Promise((resolve, reject) => {
      this.goeasy.connect({
        id: this.id,
        data: this.data,
        onSuccess: function () {
          resolve();
          //连接成功
        },
        onFailed: function (error) {
          reject();
          //连接失败
          console.log("GoEasy is failed", error);
        },
        onProgress: function (attempts) {
          //连接或自动重连中
          console.log("GoEasy is connecting", attempts);
        },
      });
    });
  }

  async createGroup() {}

  async getGroupList() {
    return await new Promise((resolve, reject) => {
      this.goeasy.im.latestConversations({
        onSuccess: function (result) {
          resolve(result);
        },
        onFailed: function (error) {
          //获取失败
          reject();
          console.log(
            "Failed to get the latest conversations, code:" +
              error.code +
              " content:" +
              error.content
          );
        },
      });
    });
  }

  async joinGroup(param) {
    await new Promise((resolve, reject) => {
      this.goeasy.im.subscribeGroup({
        groupIds: param.groupID,
        onSuccess: function () {
          resolve();
          console.log("订阅群消息成功");
        },
        onFailed: function (error) {
          reject(error);
          //订阅失败
          console.log("订阅群消息失败");
        },
      });
    });
  }

  async leaveGroup(groupId) {
    this.unsubscribeGroup(groupId);
  }

  async dismissGroup(groupId) {
    this.unsubscribeGroup(groupId);
  }

  async sendMessage(param) {
    await new Promise((resolve, reject) => {
      this.goeasy.im.sendMessage({
        message: this.messageType(param),
        onSuccess: function (message) {
          resolve(message);
          console.log(message);
        },
        onFailed: function (error) {
          reject();
          //发送失败d
          console.log(
            "Failed to sendMessage, code:" +
              error
          );
        },
      });
    });
  }

  async markMessageRead(param) {
    if (param.type == "private") {
      await new Promise((resolve, reject) => {
        this.goeasy.im.markPrivateMessageAsRead({
          userId: param.id,
          onSuccess: function () {
            resolve();
            //标记成功
            console.log("Marked as private read successfully.");
          },
          onFailed: function (error) {
            reject();
            //标记失败
            console.log(
              "Failed to mark as read, code:" +
                error.code +
                " content:" +
                error.content
            );
          },
        });
      });
    } else {
      await new Promise((resolve, reject) => {
        this.goeasy.im.markGroupMessageAsRead({
          groupId: param.id,
          onSuccess: function () {
            resolve();
            //标记成功
            console.log("Marked as group read successfully.");
          },
          onFailed: function (error) {
            reject();
            //标记失败
            console.log(
              "Failed to mark as read, code:" +
                error.code +
                " content:" +
                error.content
            );
          },
        });
      });
    }
  }

  async revokeMessage() {}

  async resendMessage() {}

  async deleteMessage() {}

  async getMessageList(param) {
    if (param.type == "private") {
      return await new Promise((resolve, reject) => {
        this.goeasy.im.history({
          userId: param.id,
          lastTimestamp: Date.now(),
          limit: 15,
          onSuccess: function (result) {
            resolve(result);
            //群聊历史消息result示例
            console.log(
              "Query group chat history successfully, result:\n " +
                JSON.stringify(result)
            );
          },
          onFailed: function (error) {
            reject();
            //获取失败
            console.log(
              "Failed to query group message, code:" +
                error.code +
                " content:" +
                error.content
            );
          },
        });
      });
    } else {
      return await new Promise((resolve, reject) => {
        this.goeasy.im.history({
          groupId: param.id,
          lastTimestamp: Date.now(),
          limit: 15,
          onSuccess: function (result) {
            resolve(result);
            //群聊历史消息result示例
            console.log(
              "Query group chat history successfully, result:\n " +
                JSON.stringify(result)
            );
          },
          onFailed: function (error) {
            reject();
            //获取失败
            console.log(
              "Failed to query group message, code:" +
                error.code +
                " content:" +
                error.content
            );
          },
        });
      });
    }
  }

  async subscribeGroup(groups, callback) {
    var onGroupMessageReceived = function (message) {
      callback([message]);
    };
    //接收群消息
    this.goeasy.im.on(
      GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED,
      onGroupMessageReceived
    );


    this.goeasy.im.subscribeGroup({
      groupIds:groups,
      onSuccess: function () {  //订阅成功
         console.log("Group message subscribe successfully.");
      },
      onFailed: function (error) { //订阅失败
         console.log("Failed to subscribe group message, code:" + error.code + " content:" + error.content);
      }
  });
  }

  unsubscribeGroup(groupId) {
    this.goeasy.im.unsubscribeGroup({
      groupId: groupId,
      onSuccess: function (message) {
        //取消成功
        console.log("Group message unsubscribe successfully.");
      },
      onFailed: function (error) {
        //取消失败
        console.log(
          "Failed to unsubscribe group message, code:" +
            error.code +
            " content:" +
            error.content
        );
      },
    });
  }

  messageType(param) {
    console.log(param);
    let message = null;
    if (param.messageType == "text") {
      message = this.goeasy.im.createTextMessage({
        text: param.message.content,
        to: {
          type: GoEasy.IM_SCENE[param.message.type],
          id: param.message.id,
          data: { avatar: "", nickname: "" },
        },
      });
    } else if (param.messageType == "image") {
      message = this.goeasy.im.createImageMessage({
        file: param.message.content,
        to: {
          type: GoEasy.IM_SCENE[param.message.type],
          id: param.message.id,
          data: { avatar: "", nickname: "" },
        },
        onProgress: function (event) {
          console.log("file uploading:", event);
        },
      });
    } else if (param.messageType == "audio") {
      message = this.goeasy.im.createAudioMessage({
        file: param.message.content,
        to: {
          type: GoEasy.IM_SCENE[param.message.type],
          id: param.message.id,
          data: { avatar: "", nickname: "" },
        },
        onProgress: function (event) {
          console.log("file uploading:", event);
        },
      });
    } else if (param.messageType == "video") {
      message = this.goeasy.im.createVideoMessage({
        file: param.message.content,
        to: {
          type: GoEasy.IM_SCENE[param.message.type],
          id: param.message.id,
          data: { avatar: "", nickname: "" },
        },
        onProgress: function (event) {
          console.log("file uploading:", event);
        },
      });
    } else if (param.messageType == "file") {
      message = this.goeasy.im.createFileMessage({
        file: param.message.content,
        to: {
          type: GoEasy.IM_SCENE[param.message.type],
          id: param.message.id,
          data: { avatar: "", nickname: "" },
        },
        onProgress: function (event) {
          console.log("file uploading:", event);
        },
      });
    } else if (param.messageType == "custom") {
      message = this.goeasy.im.createCustomMessage({
        type: 'custom',
        payload: param.message.payload,
        to: {
          type: GoEasy.IM_SCENE[param.message.type],
          id: param.message.id,
          data: { avatar: "", nickname: "" },
        },
        onProgress: function (event) {
          console.log("file uploading:", event);
        },
      });
    }

    return message;
  }
}

export default GoEasyIM;
