'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _rollupPluginBabelHelpers = require('./_rollupPluginBabelHelpers-21ae158b.js');
var topics = require('./topics-373d2156.js');
var utils = require('./utils-6a748c02.js');

/**
 * 1. UIKit Instances
 *    a. getSdk
 *    b. getPubSub
 * 2. Chat & Connection
 *    a. getConnect
 *    b. getDisconnect
 *    c. getUpdateUserInfo
 * 3. Channel
 *    a. getCreateGroupChannel
 *    b. getCreateOpenChannel
 *    c. getGetGroupChannel
 *    d. getGetOpenChannel
 *    e. getLeaveGroupChannel
 *    f. getEnterOpenChannel
 *    g. getExitOpenChannel
 *    h. getFreezeChannel
 *    i. getUnfreezeChannel
 * 4. Message
 *    a. getSendUserMessage
 *    b. getSendFileMessage
 *    c. getUpdateUserMessage
 *    d. x - getUpdateFileMessage
 *    e. getDeleteMessage
 *    f. getResendUserMessage
 *    g. getResendFileMessage
 */

/**
 * import useSendbirdStateContext from '@sendbird-uikit/useSendbirdStateContext'
 * import selectors from '@sendbird-uikit/send'
 * const state = useSendbirdStateContext();
 */

// 1. UIKit Instances

/**
 * const sdk = selectors.getSdk(state);
 */
const getSdk = state => {
  const {
    stores = {}
  } = state;
  const {
    sdkStore = {}
  } = stores;
  const {
    sdk
  } = sdkStore;
  return sdk;
};

/**
 * const pubSub = selectors.getPubSub(state);
 */
const getPubSub = state => {
  const {
    config = {}
  } = state;
  const {
    pubSub
  } = config;
  return pubSub;
};

// 2. Chat & Connection

/**
 * const connect = selectors.getConnect(state);
 * connect('user-id-sendbirdian', 'access-token-0000')
 *  .then((user) => {})
 *  .catch((error) => {})
 */
const getConnect = state => (userId, accessToken) => new Promise((resolve, reject) => {
  const sdk = getSdk(state);
  if (!sdk) {
    reject(new Error('Sdk not found'));
  }
  if (!(sdk !== null && sdk !== void 0 && sdk.connect && typeof sdk.connect === 'function')) {
    reject(new Error('Not found the function "connect'));
  }
  if (!accessToken) {
    sdk.connect(userId).then(res => resolve(res)).catch(err => reject(err));
  } else {
    sdk.connect(userId, accessToken).then(res => resolve(res)).catch(err => reject(err));
  }
});

/**
 * const disconnect = selectors.getDisconnect(state);
 * disconnect()
 *  .then(() => {})
 *  .catch((error) => {})
 */
const getDisconnect = state => () => new Promise((resolve, reject) => {
  const sdk = getSdk(state);
  if (!sdk) {
    reject(new Error('Sdk not found'));
  }
  if (!(sdk.disconnect && typeof sdk.disconnect === 'function')) {
    reject(new Error('Not found the function "disconnect'));
  }
  sdk.disconnect().then(res => resolve(res)).catch(err => reject(err));
});

/**
 * const updateUserInfo = selectors.getUpdateUserInfo(state);
 * updateUserInfo('new-nickname', 'new-profile-url')
 *  .then((user) => {})
 *  .catch((error) => {})
 */
const getUpdateUserInfo = state => (nickname, profileUrl) => new Promise((resolve, reject) => {
  const sdk = getSdk(state);
  if (!sdk) {
    reject(new Error('Sdk not found'));
  }
  if (!(sdk.updateCurrentUserInfo && typeof sdk.updateCurrentUserInfo === 'function')) {
    reject(new Error('Not found the function "updateCurrentUserInfo"'));
  }
  const userParams = {
    nickname
  };
  if (profileUrl) {
    userParams.profileUrl = profileUrl;
  }
  sdk.updateCurrentUserInfo(userParams).then(res => resolve(res)).catch(err => reject(err));
});

// 3. Channel

/**
 * const createGroupChannel = selectors.getCreateGroupChannel(state);
 * createGroupChannel(channelParams: GroupChannelCreateParams)
 *  .then((channel) => {})
 *  .catch((error) => {})
 */
const getCreateGroupChannel = state => params => new Promise((resolve, reject) => {
  const sdk = getSdk(state);
  const pubSub = getPubSub(state);
  if (!sdk) {
    reject(new Error('Sdk not found'));
  }
  if (!sdk.groupChannel) {
    reject(new Error('Not found GroupChannelModule'));
  }
  if (!(sdk.groupChannel.createChannel && typeof sdk.groupChannel.createChannel === 'function')) {
    reject(new Error('Not found the function "createChannel"'));
  }
  sdk.groupChannel.createChannel(params).then(channel => {
    resolve(channel);
    pubSub.publish(topics.PUBSUB_TOPICS.CREATE_CHANNEL, {
      channel
    });
  }).catch(reject);
});

/**
 * const createOpenChannel = selectors.getCreateOpenChannel(state);
 * createOpenChannel(channelParams: OpenChannelCreateParams)
 *  .then((channel) => {})
 *  .catch((error) => {})
 */
const getCreateOpenChannel = state => params => new Promise((resolve, reject) => {
  const sdk = getSdk(state);
  // const pubSub = getPubSub(state);
  if (!sdk) {
    reject(new Error('Sdk not found'));
  }
  if (!sdk.openChannel) {
    reject(new Error('Not found OpenChannelModule'));
  }
  if (!(sdk.openChannel.createChannel && typeof sdk.openChannel.createChannel === 'function')) {
    reject(new Error('Not found the function "createChannel"'));
  }
  sdk.openChannel.createChannel(params).then(channel => {
    resolve(channel);
    // Consider pubSub process
  }).catch(reject);
});

/**
 * const getGroupChannel = selectors.getGetGroupChannel(state);
 * getGroupChannel('channel-url-1234', isSelected)
 *  .then((channel) => {
 *    // groupChannel = channel;
 *    // or
 *    // setCurrentChannel(channel);
 *  })
 *  .catch((error) => {})
 */
const getGetGroupChannel = state => channelUrl => new Promise((resolve, reject) => {
  const sdk = getSdk(state);
  // const pubSub = getPubSub(state);
  if (!sdk) {
    reject(new Error('Sdk not found'));
  }
  if (!sdk.groupChannel) {
    reject(new Error('Not found GroupChannelModule'));
  }
  if (!(sdk.groupChannel.getChannel && typeof sdk.groupChannel.getChannel === 'function')) {
    reject(new Error('Not found the function "getChannel"'));
  }
  sdk.groupChannel.getChannel(channelUrl).then(channel => {
    resolve(channel);
    // Add pubSub with isSelected
  }).catch(reject);
});

/**
 * const getOpenChannel = selectors.getGetOpenChannel(state);
 * getOpenChannel('channel-url-12345')
 *  .then((channel) => {
 *    // openChannel = channel;
 *    // or
 *    // setCurrentChannel(channel);
 *  })
 *  .catch((error) => {})
 */
const getGetOpenChannel = state => channelUrl => new Promise((resolve, reject) => {
  const sdk = getSdk(state);
  // const pubSub = getPubSub(state);
  if (!sdk) {
    reject(new Error('Sdk not found'));
  }
  if (!sdk.openChannel) {
    reject(new Error('Not found OpenChannelModule'));
  }
  if (!(sdk.openChannel.getChannel && typeof sdk.openChannel.getChannel === 'function')) {
    reject(new Error('Not found the function "getChannel"'));
  }
  sdk.openChannel.getChannel(channelUrl).then(channel => {
    resolve(channel);
    // Add pubSub with isSelected
  }).catch(reject);
});

/**
 * const leaveChannel = selectors.getLeaveGroupChannel(state);
 * leaveChannel('group-channel-url')
 *  .then((channel) => {})
 *  .catch((error) => {})
 */
const getLeaveGroupChannel = state => channelUrl => new Promise((resolve, reject) => {
  var _getGetGroupChannel;
  (_getGetGroupChannel = getGetGroupChannel(state)) === null || _getGetGroupChannel === void 0 ? void 0 : _getGetGroupChannel(channelUrl).then(channel => {
    channel.leave().then(() => {
      resolve();
      // Add pubSub process
    }).catch(reject);
  }).catch(reject);
});

/**
 * const enterChannel = selectors.getEnterOpenChannel(state);
 * enterChannel('open-channel-url')
 *  .then((channel) => {})
 *  .catch((error) => {})
 */
const getEnterOpenChannel = state => channelUrl => new Promise((resolve, reject) => {
  var _getGetOpenChannel;
  (_getGetOpenChannel = getGetOpenChannel(state)) === null || _getGetOpenChannel === void 0 ? void 0 : _getGetOpenChannel(channelUrl).then(channel => {
    channel.enter().then(() => {
      resolve(channel);
      // Add pubSub process
    }).catch(reject);
  }).catch(reject);
});

/**
 * const exitChannel = selectors.getExitOpenChannel(state);
 * exitChannel('open-channel-url')
 *  .then((channel) => {})
 *  .catch((error) => {})
 */
const getExitOpenChannel = state => channelUrl => new Promise((resolve, reject) => {
  var _getGetOpenChannel2;
  (_getGetOpenChannel2 = getGetOpenChannel(state)) === null || _getGetOpenChannel2 === void 0 ? void 0 : _getGetOpenChannel2(channelUrl).then(channel => {
    channel.exit().then(() => {
      resolve(channel);
      // Add pubSub process
    }).catch(reject);
  }).catch(reject);
});

/**
 * const freezeChannel = selectors.getFreezeChannel(currentChannel);
 * freezeChannel()
 *  .then(() => {})
 *  .catch((error) => {})
 */
const getFreezeChannel = () => channel => new Promise((resolve, reject) => {
  if (!(channel.freeze && typeof (channel === null || channel === void 0 ? void 0 : channel.freeze) === 'function')) {
    reject(new Error('Not found the function "freeze"'));
  }
  channel.freeze().then(() => {
    resolve();
    // Add pubSub process
    /**
     * consider divide the logic to
     * _freezeGroupChannel and _freezeOpenChannel
     */
  }).catch(reject);
});

/**
 * const unfreezeChannel = selectors.getUnfreezeChannel(currentChannel);
 * unfreezeChannel()
 *  .then((channel) => {})
 *  .catch((error) => {})
 */
const getUnfreezeChannel = () => channel => new Promise((resolve, reject) => {
  if (!(channel.unfreeze && typeof (channel === null || channel === void 0 ? void 0 : channel.unfreeze) === 'function')) {
    reject(new Error('Not found the function "unfreeze"'));
  }
  channel.unfreeze().then(() => {
    resolve();
    // Add pubSub process
    /**
     * consider divide the logic to
     * _unfreezeGroupChannel and _unfreezeOpenChannel
     */
  }).catch(reject);
});

// 4. Message
class UikitMessageHandler {
  constructor() {
    _rollupPluginBabelHelpers._defineProperty(this, "_onPending", utils.noop);
    _rollupPluginBabelHelpers._defineProperty(this, "_onFailed", utils.noop);
    _rollupPluginBabelHelpers._defineProperty(this, "_onSucceeded", utils.noop);
  }
  triggerPending(message) {
    this._onPending(message);
  }
  triggerFailed(error, message) {
    this._onFailed(error, message.isResendable ? message : null);
  }
  triggerSucceeded(message) {
    this._onSucceeded(message);
  }
  onPending(handler) {
    if (typeof handler === 'function') {
      this._onPending = handler;
    }
    return this;
  }
  onFailed(handler) {
    if (typeof handler === 'function') {
      this._onFailed = handler;
    }
    return this;
  }
  onSucceeded(handler) {
    if (typeof handler === 'function') {
      this._onSucceeded = handler;
    }
    return this;
  }
}

/**
 * const sendUserMessage = selectors.getSendUserMessage(state);
 * sendUserMessage(
 *  channel: GroupChannel | OpenChannel,
 *  params: UserMessageCreateParams,
 * )
 *  .onPending((message) => {})
 *  .onFailed((error, message) => {})
 *  .onSucceeded((message) => {})
 */

const getSendUserMessage = state => (channel, params) => {
  const handler = new UikitMessageHandler();
  const pubSub = getPubSub(state);
  channel.sendUserMessage(params).onFailed((error, message) => handler.triggerFailed(error, message)).onPending(message => {
    pubSub.publish(topics.PUBSUB_TOPICS.SEND_MESSAGE_START, {
      message,
      channel
    });
    handler.triggerPending(message);
  }).onSucceeded(message => {
    pubSub.publish(topics.PUBSUB_TOPICS.SEND_USER_MESSAGE, {
      message,
      channel
    });
    handler.triggerSucceeded(message);
  });
  return handler;
};

/**
 * const sendFileMessage = selectors.getSendFileMessage(state);
 * sendFileMessage(
 *  channel: GroupChannel | OpenChannel,
 *  params: FileMessageCreateParams,
 * )
 *  .onPending((message) => {})
 *  .onFailed((error, message) => {})
 *  .onSucceeded((message) => {})
 */
const getSendFileMessage = state => (channel, params) => {
  const handler = new UikitMessageHandler();
  const pubSub = getPubSub(state);
  channel.sendFileMessage(params).onFailed((error, message) => handler.triggerFailed(error, message)).onPending(message => {
    pubSub.publish(topics.PUBSUB_TOPICS.SEND_MESSAGE_START, {
      message,
      channel
    });
    handler.triggerPending(message);
  }).onSucceeded(message => {
    pubSub.publish(topics.PUBSUB_TOPICS.SEND_FILE_MESSAGE, {
      message,
      channel
    });
    handler.triggerSucceeded(message);
  });
  return handler;
};

/**
 * const updateUserMessage = selectors.getUpdateUserMessage(state);
 * updateUserMessage(
 *  channel: GroupChannel | OpenChannel,
 *  messageId: number,
 *  messageParams: UserMessageUpdateParams,
 * )
 *  .then((message) => {})
 *  .catch((error) => {})
 */
const getUpdateUserMessage = state => (channel, messageId, params) => new Promise((resolve, reject) => {
  const pubSub = getPubSub(state);
  channel.updateUserMessage(messageId, params).then(message => {
    pubSub.publish(topics.PUBSUB_TOPICS.UPDATE_USER_MESSAGE, {
      message,
      channel,
      fromSelector: true
    });
    resolve(message);
  }).catch(reject);
});

// TODO: We will provie this function in the future
/**
 * const updateFileMessage = selectors.getUpdateFileMessage(state);
 * updateFileMessage(
 *  channel: GroupChannel | OpenChannel,
 *  messageId: number,
 *  params: FileMessageUpdateParams,
 * )
 *  .then((message) => {})
 *  .catch((error) => {})
 */
// const getUpdateFileMessage = (state: SendBirdState) => (
//   (channel: GroupChannel | OpenChannel, messageId: number, params: FileMessageUpdateParams) => (
//     new Promise((resolve, reject) => {
//       const pubSub = getPubSub(state);
//       channel.updateFileMessage(messageId, params)
//         .then((message) => {
//           pubSub.publish(
//             topics.UPDATE_USER_MESSAGE,
//             { message, channel, fromSelector: true },
//           );
//           resolve(message);
//         })
//         .catch(reject);
//     })
//   )
// );

/**
 * const deleteMessage = selectors.getDeleteMessage(state);
 * deleteMessage(
 *  channel: GroupChannel | OpenChannel,
 *  message: SendableMessage,
 * )
 *  .then((deletedMessage) => {})
 *  .catch((error) => {})
 */
const getDeleteMessage = state => (channel, message) => new Promise((resolve, reject) => {
  const pubSub = getPubSub(state);
  const {
    messageId
  } = message;
  channel.deleteMessage(message).then(() => {
    pubSub.publish(topics.PUBSUB_TOPICS.DELETE_MESSAGE, {
      messageId,
      channel
    });
    resolve(message);
  }).catch(reject);
});

/**
 * const resendUserMessage = selectors.getResendUserMessage(state);
 * resendUserMessage(
 *  channel: GroupChannel | OpenChannel,
 *  failedMessage: UserMessage,
 * )
 *  .then(() => {})
 *  .catch((error) => {})
 */
const getResendUserMessage = state => (channel, failedMessage) => new Promise((resolve, reject) => {
  const pubSub = getPubSub(state);
  channel.resendUserMessage(failedMessage).then(message => {
    pubSub.publish(topics.PUBSUB_TOPICS.SEND_USER_MESSAGE, {
      message,
      channel
    });
    resolve(message);
  }).catch(reject);
});

/**
 * const resendFileMessage = selectors.getResendFileMessage(state);
 * resendFileMessage(
 *  channel: GroupChannel | OpenChannel,
 *  failedMessage: FileMessage,
 *  blob: Blob,
 * )
 *  .then(() => {})
 *  .catch((error) => {})
 */
const getResendFileMessage = state => (channel, failedMessage, blob) => new Promise((resolve, reject) => {
  const pubSub = getPubSub(state);
  channel.resendFileMessage(failedMessage, blob).then(message => {
    pubSub.publish(topics.PUBSUB_TOPICS.SEND_FILE_MESSAGE, {
      message,
      channel
    });
    resolve(message);
  }).catch(reject);
});
const sendbirdSelectors = {
  getSdk,
  getPubSub,
  getConnect,
  getDisconnect,
  getUpdateUserInfo,
  getCreateGroupChannel,
  getCreateOpenChannel,
  getGetGroupChannel,
  getGetOpenChannel,
  getLeaveGroupChannel,
  getEnterOpenChannel,
  getExitOpenChannel,
  getFreezeChannel,
  getUnfreezeChannel,
  getSendUserMessage,
  getSendFileMessage,
  getUpdateUserMessage,
  getDeleteMessage,
  getResendUserMessage,
  getResendFileMessage
};

exports.UikitMessageHandler = UikitMessageHandler;
exports["default"] = sendbirdSelectors;
exports.getConnect = getConnect;
exports.getCreateGroupChannel = getCreateGroupChannel;
exports.getCreateOpenChannel = getCreateOpenChannel;
exports.getDeleteMessage = getDeleteMessage;
exports.getDisconnect = getDisconnect;
exports.getEnterOpenChannel = getEnterOpenChannel;
exports.getExitOpenChannel = getExitOpenChannel;
exports.getFreezeChannel = getFreezeChannel;
exports.getGetGroupChannel = getGetGroupChannel;
exports.getGetOpenChannel = getGetOpenChannel;
exports.getLeaveGroupChannel = getLeaveGroupChannel;
exports.getPubSub = getPubSub;
exports.getResendFileMessage = getResendFileMessage;
exports.getResendUserMessage = getResendUserMessage;
exports.getSdk = getSdk;
exports.getSendFileMessage = getSendFileMessage;
exports.getSendUserMessage = getSendUserMessage;
exports.getUnfreezeChannel = getUnfreezeChannel;
exports.getUpdateUserInfo = getUpdateUserInfo;
exports.getUpdateUserMessage = getUpdateUserMessage;
//# sourceMappingURL=sendbirdSelectors.js.map
