'use strict';

var React = require('react');
var topics = require('./topics-e24ef339.js');
var useSendbirdStateContext = require('./useSendbirdStateContext.js');
var _rollupPluginBabelHelpers = require('./_rollupPluginBabelHelpers-acf412a3.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

let OpenChannelListFetchingStatus = /*#__PURE__*/function (OpenChannelListFetchingStatus) {
  OpenChannelListFetchingStatus["EMPTY"] = "EMPTY";
  OpenChannelListFetchingStatus["FETCHING"] = "FETCHING";
  OpenChannelListFetchingStatus["DONE"] = "DONE";
  OpenChannelListFetchingStatus["ERROR"] = "ERROR";
  return OpenChannelListFetchingStatus;
}({});

var OpenChannelListActionTypes = /*#__PURE__*/function (OpenChannelListActionTypes) {
  OpenChannelListActionTypes["INIT_OPEN_CHANNEL_LIST_START"] = "INIT_OPEN_CHANNEL_LIST_START";
  OpenChannelListActionTypes["INIT_OPEN_CHANNEL_LIST_SUCCESS"] = "INIT_OPEN_CHANNEL_LIST_SUCCESS";
  OpenChannelListActionTypes["INIT_OPEN_CHANNEL_LIST_FAILURE"] = "INIT_OPEN_CHANNEL_LIST_FAILURE";
  OpenChannelListActionTypes["RESET_OPEN_CHANNEL_LIST"] = "RESET_OPEN_CHANNEL_LIST";
  OpenChannelListActionTypes["FETCH_OPEN_CHANNEL_LIST_START"] = "FETCH_OPEN_CHANNEL_LIST_START";
  OpenChannelListActionTypes["FETCH_OPEN_CHANNEL_LIST_SUCCESS"] = "FETCH_OPEN_CHANNEL_LIST_SUCCESS";
  OpenChannelListActionTypes["FETCH_OPEN_CHANNEL_LIST_FAILURE"] = "FETCH_OPEN_CHANNEL_LIST_FAILURE";
  OpenChannelListActionTypes["CREATE_OPEN_CHANNEL"] = "CREATE_OPEN_CHANNEL";
  OpenChannelListActionTypes["SET_CURRENT_OPEN_CHANNEL"] = "SET_CURRENT_OPEN_CHANNEL";
  OpenChannelListActionTypes["UPDATE_OPEN_CHANNEL_LIST_QUERY"] = "UPDATE_OPEN_CHANNEL_LIST_QUERY";
  OpenChannelListActionTypes["UPDATE_OPEN_CHANNEL"] = "UPDATE_OPEN_CHANNEL";
  return OpenChannelListActionTypes;
}(OpenChannelListActionTypes || {});

function reducer(state, action) {
  switch (action.type) {
    case OpenChannelListActionTypes.INIT_OPEN_CHANNEL_LIST_START:
      {
        return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, state), {}, {
          fetchingStatus: OpenChannelListFetchingStatus.FETCHING
        });
      }
    case OpenChannelListActionTypes.INIT_OPEN_CHANNEL_LIST_SUCCESS:
      {
        const channelList = action.payload;
        return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, state), {}, {
          allChannels: channelList,
          fetchingStatus: channelList.length > 0 ? OpenChannelListFetchingStatus.DONE : OpenChannelListFetchingStatus.EMPTY
        });
      }
    case OpenChannelListActionTypes.INIT_OPEN_CHANNEL_LIST_FAILURE:
      {
        return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, state), {}, {
          allChannels: [],
          fetchingStatus: OpenChannelListFetchingStatus.ERROR
        });
      }
    case OpenChannelListActionTypes.RESET_OPEN_CHANNEL_LIST:
      {
        return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, state), {}, {
          allChannels: [],
          fetchingStatus: OpenChannelListFetchingStatus.EMPTY
        });
      }
    case OpenChannelListActionTypes.FETCH_OPEN_CHANNEL_LIST_START:
      {
        return state;
      }
    case OpenChannelListActionTypes.FETCH_OPEN_CHANNEL_LIST_SUCCESS:
      {
        return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, state), {}, {
          allChannels: [...state.allChannels, ...action.payload]
        });
      }
    case OpenChannelListActionTypes.FETCH_OPEN_CHANNEL_LIST_FAILURE:
      {
        return state;
      }
    case OpenChannelListActionTypes.CREATE_OPEN_CHANNEL:
      {
        return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, state), {}, {
          currentChannel: action.payload,
          allChannels: [action.payload, ...state.allChannels]
        });
      }
    case OpenChannelListActionTypes.SET_CURRENT_OPEN_CHANNEL:
      {
        return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, state), {}, {
          currentChannel: action.payload
        });
      }
    case OpenChannelListActionTypes.UPDATE_OPEN_CHANNEL_LIST_QUERY:
      {
        return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, state), {}, {
          channelListQuery: action === null || action === void 0 ? void 0 : action.payload
        });
      }
    case OpenChannelListActionTypes.UPDATE_OPEN_CHANNEL:
      {
        var _state$currentChannel, _action$payload2;
        return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, state), {}, {
          allChannels: state.allChannels.map(channel => {
            var _action$payload;
            return (channel === null || channel === void 0 ? void 0 : channel.url) === ((_action$payload = action.payload) === null || _action$payload === void 0 ? void 0 : _action$payload.url) ? action.payload : channel;
          }),
          currentChannel: ((_state$currentChannel = state.currentChannel) === null || _state$currentChannel === void 0 ? void 0 : _state$currentChannel.url) === (action === null || action === void 0 ? void 0 : (_action$payload2 = action.payload) === null || _action$payload2 === void 0 ? void 0 : _action$payload2.url) ? state.currentChannel : action.payload
        });
      }
    default:
      {
        return state;
      }
  }
}

var openChannelListInitialState = {
  allChannels: [],
  currentChannel: null,
  fetchingStatus: OpenChannelListFetchingStatus.EMPTY,
  channelListQuery: null
};

function useFetchNextCallback(_ref, _ref2) {
  let {
    sdkInitialized,
    openChannelListQuery
  } = _ref;
  let {
    logger,
    openChannelListDispatcher
  } = _ref2;
  return React.useCallback(callback => {
    if (sdkInitialized && openChannelListQuery !== null && openChannelListQuery !== void 0 && openChannelListQuery.hasNext) {
      logger.info('OpenChannelList|useFetchNextCallback : Fetch channels');
      openChannelListDispatcher({
        type: OpenChannelListActionTypes.FETCH_OPEN_CHANNEL_LIST_START,
        payload: null
      });
      openChannelListQuery.next().then(channelList => {
        callback(channelList, null);
        logger.info('OpenChannelList|useFetchNextCallback: Succeeded fetching channels', channelList);
        openChannelListDispatcher({
          type: OpenChannelListActionTypes.FETCH_OPEN_CHANNEL_LIST_SUCCESS,
          payload: channelList
        });
      }).catch(err => {
        callback(null, err);
        logger.error('OpenChannelList|useFetchNextCallback: Failed fetching channels', err);
        openChannelListDispatcher({
          type: OpenChannelListActionTypes.FETCH_OPEN_CHANNEL_LIST_FAILURE,
          payload: null
        });
      });
    } else {
      logger.info('OpenChannelList|useFetchNextCallback : There is no more channels');
    }
  }, [sdkInitialized, openChannelListQuery]);
}

function createChannelListQuery(_ref) {
  var _sdk$openChannel, _sdk$openChannel$crea;
  let {
    sdk,
    logMessage,
    openChannelListQuery,
    logger,
    openChannelListDispatcher
  } = _ref;
  const params = {};
  params.limit = 20;
  params.includeFrozen = true;
  if (openChannelListQuery) {
    Object.keys(openChannelListQuery).forEach(key => {
      params[key] = openChannelListQuery[key];
    });
  }
  const channelListQuery = sdk === null || sdk === void 0 ? void 0 : (_sdk$openChannel = sdk.openChannel) === null || _sdk$openChannel === void 0 ? void 0 : (_sdk$openChannel$crea = _sdk$openChannel.createOpenChannelListQuery) === null || _sdk$openChannel$crea === void 0 ? void 0 : _sdk$openChannel$crea.call(_sdk$openChannel, params);
  logger.info(logMessage, channelListQuery);
  openChannelListDispatcher({
    type: OpenChannelListActionTypes.UPDATE_OPEN_CHANNEL_LIST_QUERY,
    payload: channelListQuery
  });
  return channelListQuery;
}

function useSetupOpenChannelList(_ref, _ref2) {
  let {
    sdk,
    sdkInitialized,
    openChannelListQuery
  } = _ref;
  let {
    logger,
    openChannelListDispatcher
  } = _ref2;
  React.useEffect(() => {
    if (sdkInitialized) {
      if (sdk !== null && sdk !== void 0 && sdk.openChannel) {
        var _sdk$openChannel;
        if (sdk !== null && sdk !== void 0 && (_sdk$openChannel = sdk.openChannel) !== null && _sdk$openChannel !== void 0 && _sdk$openChannel.createOpenChannelListQuery) {
          logger.info('OpenChannelList|useSetupOpenChannelList: Setup OpenChannelList', {
            sdkInitialized
          });
          const channelListQuery = createChannelListQuery({
            sdk,
            logger,
            openChannelListQuery,
            openChannelListDispatcher,
            logMessage: 'OpenChannelList|useSetupOpenChannelList: Succeeded create channelListQuery'
          });
          if (channelListQuery !== null && channelListQuery !== void 0 && channelListQuery.hasNext) {
            logger.info('OpenChannelList|useSetupOpenChannelList: Fetch channels');
            openChannelListDispatcher({
              type: OpenChannelListActionTypes.INIT_OPEN_CHANNEL_LIST_START,
              payload: null
            });
            channelListQuery.next().then(channelList => {
              logger.info('OpenChannelList|useSetupOpenChannelList: Succeeded fetching channels', channelList);
              openChannelListDispatcher({
                type: OpenChannelListActionTypes.INIT_OPEN_CHANNEL_LIST_SUCCESS,
                payload: channelList
              });
            }).catch(err => {
              logger.error('OpenChannelList|useSetupOpenChannelList: Failed fetching channels', err);
              openChannelListDispatcher({
                type: OpenChannelListActionTypes.INIT_OPEN_CHANNEL_LIST_FAILURE,
                payload: null
              });
            });
          } else {
            logger.info('OpenChannelList|useSetupOpenChannelList: There is no more channels');
          }
        } else {
          logger.warning('OpenChannelList|useSetupOpenChannelList: createOpenChannelListQuery is not included in the openChannel', sdk.openChannel);
        }
      } else {
        logger.warning('OpenChannelList|useSetupOpenChannelList: openChannel is not included in the Chat SDK', sdk);
      }
    } else {
      logger.info('OpenChannelList|useSetupOpenChannelList: Reset OpenChannelList', {
        sdkInitialized
      });
      openChannelListDispatcher({
        type: OpenChannelListActionTypes.RESET_OPEN_CHANNEL_LIST,
        payload: null
      });
    }
  }, [sdkInitialized, openChannelListQuery]);
}

function useRefreshOpenChannelList(_ref, _ref2) {
  let {
    sdk,
    sdkInitialized,
    openChannelListQuery
  } = _ref;
  let {
    logger,
    openChannelListDispatcher
  } = _ref2;
  return React.useCallback(() => {
    var _sdk$openChannel;
    if (!sdkInitialized) {
      logger.info('OpenChannelList|useRefreshOpenChannelList: Reset OpenChannelList', {
        sdkInitialized
      });
      openChannelListDispatcher({
        type: OpenChannelListActionTypes.RESET_OPEN_CHANNEL_LIST,
        payload: null
      });
      return;
    }
    if (!(sdk !== null && sdk !== void 0 && sdk.openChannel)) {
      logger.warning('OpenChannelList|useRefreshOpenChannelList: openChannel is not included in the Chat SDK', sdk);
      return;
    }
    if (!(sdk !== null && sdk !== void 0 && (_sdk$openChannel = sdk.openChannel) !== null && _sdk$openChannel !== void 0 && _sdk$openChannel.createOpenChannelListQuery)) {
      logger.warning('OpenChannelList|useRefreshOpenChannelList: createOpenChannelListQuery is not included in the openChannel', sdk.openChannel);
      return;
    }
    logger.info('OpenChannelList|useRefreshOpenChannelList: Setup OpenChannelList', {
      sdkInitialized
    });
    const channelListQuery = createChannelListQuery({
      sdk,
      logger,
      openChannelListQuery,
      openChannelListDispatcher,
      logMessage: 'OpenChannelList|useRefreshOpenChannelList: Succeeded create channelListQuery'
    });
    if (channelListQuery.hasNext) {
      logger.info('OpenChannelList|useRefreshOpenChannelList: Fetch channels');
      openChannelListDispatcher({
        type: OpenChannelListActionTypes.INIT_OPEN_CHANNEL_LIST_START,
        payload: null
      });
      channelListQuery.next().then(channelList => {
        logger.info('OpenChannelList|useRefreshOpenChannelList: Succeeded fetching channels', channelList);
        openChannelListDispatcher({
          type: OpenChannelListActionTypes.INIT_OPEN_CHANNEL_LIST_SUCCESS,
          payload: channelList
        });
      }).catch(err => {
        logger.error('OpenChannelList|useRefreshOpenChannelList: Failed fetching channels', err);
        openChannelListDispatcher({
          type: OpenChannelListActionTypes.INIT_OPEN_CHANNEL_LIST_FAILURE,
          payload: null
        });
      });
    } else {
      logger.info('OpenChannelList|useRefreshOpenChannelList: There is no more channels');
    }
  }, [sdkInitialized, openChannelListQuery]);
}

const OpenChannelListContext = /*#__PURE__*/React__default["default"].createContext({
  onChannelSelected: null,
  currentChannel: null,
  allChannels: [],
  fetchingStatus: OpenChannelListFetchingStatus.EMPTY,
  customOpenChannelListQuery: {},
  fetchNextChannels: null,
  refreshOpenChannelList: null,
  openChannelListDispatcher: null,
  logger: null
});
function useOpenChannelListContext() {
  const context = React.useContext(OpenChannelListContext);
  return context;
}
const OpenChannelListProvider = _ref => {
  var _stores$sdkStore, _stores$sdkStore2;
  let {
    className,
    children,
    queries,
    onChannelSelected
  } = _ref;
  // props
  const {
    stores,
    config
  } = useSendbirdStateContext();
  const {
    logger,
    pubSub
  } = config;
  const sdk = (stores === null || stores === void 0 ? void 0 : (_stores$sdkStore = stores.sdkStore) === null || _stores$sdkStore === void 0 ? void 0 : _stores$sdkStore.sdk) || null;
  const sdkInitialized = (stores === null || stores === void 0 ? void 0 : (_stores$sdkStore2 = stores.sdkStore) === null || _stores$sdkStore2 === void 0 ? void 0 : _stores$sdkStore2.initialized) || false;
  const customOpenChannelListQuery = React.useMemo(() => {
    return (queries === null || queries === void 0 ? void 0 : queries.openChannelListQuery) || null;
  }, [queries === null || queries === void 0 ? void 0 : queries.openChannelListQuery]);

  // dux
  const [openChannelListStore, openChannelListDispatcher] = React.useReducer(reducer, openChannelListInitialState);
  const {
    allChannels,
    currentChannel,
    fetchingStatus,
    channelListQuery
  } = openChannelListStore;

  // Initialize
  useSetupOpenChannelList({
    sdk,
    sdkInitialized,
    openChannelListQuery: customOpenChannelListQuery
  }, {
    logger,
    openChannelListDispatcher
  });

  // Events & PubSub
  React.useEffect(() => {
    const subscriber = pubSub !== null && pubSub !== void 0 && pubSub.subscribe ? new Map() : null;
    subscriber === null || subscriber === void 0 ? void 0 : subscriber.set(topics.PUBSUB_TOPICS.UPDATE_OPEN_CHANNEL, pubSub === null || pubSub === void 0 ? void 0 : pubSub.subscribe(topics.PUBSUB_TOPICS.UPDATE_OPEN_CHANNEL, channel => {
      openChannelListDispatcher({
        type: OpenChannelListActionTypes.UPDATE_OPEN_CHANNEL,
        payload: channel
      });
    }));
    return () => {
      subscriber === null || subscriber === void 0 ? void 0 : subscriber.forEach(s => {
        try {
          s.remove();
        } catch (_unused) {
          //
        }
      });
    };
  }, [sdkInitialized, pubSub]);

  // Fetch next channels by scroll event
  const fetchNextChannels = useFetchNextCallback({
    sdkInitialized: sdkInitialized,
    openChannelListQuery: channelListQuery
  }, {
    logger,
    openChannelListDispatcher
  });

  // Refresh channel list by click event of 'refresh button'
  const refreshOpenChannelList = useRefreshOpenChannelList({
    sdk,
    sdkInitialized,
    openChannelListQuery: customOpenChannelListQuery
  }, {
    logger,
    openChannelListDispatcher
  });
  return /*#__PURE__*/React__default["default"].createElement(OpenChannelListContext.Provider, {
    value: {
      // props
      onChannelSelected: onChannelSelected,
      customOpenChannelListQuery: customOpenChannelListQuery,
      // interface
      logger: logger,
      currentChannel: currentChannel,
      allChannels: allChannels,
      fetchingStatus: fetchingStatus,
      fetchNextChannels: fetchNextChannels,
      refreshOpenChannelList: refreshOpenChannelList,
      openChannelListDispatcher: openChannelListDispatcher
    }
  }, /*#__PURE__*/React__default["default"].createElement("div", {
    className: `sendbird-open-channel-list ${className}`
  }, children));
};
var OpenChannelListProvider$1 = {
  OpenChannelListProvider,
  useOpenChannelListContext
};

exports.OpenChannelListActionTypes = OpenChannelListActionTypes;
exports.OpenChannelListFetchingStatus = OpenChannelListFetchingStatus;
exports.OpenChannelListProvider = OpenChannelListProvider;
exports.OpenChannelListProvider$1 = OpenChannelListProvider$1;
exports.useOpenChannelListContext = useOpenChannelListContext;
//# sourceMappingURL=OpenChannelListProvider-de00eec5.js.map
