import { useCreation } from 'ahooks';
import { getApps, getFederatedEnabled, getMaster } from '@arcblock/ux/lib/Util/federated';
import isUndefined from 'lodash/isUndefined';
import { use } from 'react';
import { SessionContext } from '../../Session/context';

/**
 *
 * @param {object} param
 * @param {object} param.blocklet
 * @param {string} param.action
 * @param {string} [param.sourceAppPid]
 * @param {object} param.connectState
 * @param {boolean} [param.enableSwitchApp]
 * @returns
 */
export default function useApps({ blocklet, action, sourceAppPid, connectState, enableSwitchApp }) {
  const sessionContext = use(SessionContext);

  const canSwitchApp = useCreation(() => {
    if (enableSwitchApp === true) {
      return true;
    }
    if (enableSwitchApp === false) {
      return false;
    }

    if (sessionContext?.session?.user) {
      if (!['login', 'invite', 'connect-to-did-space', 'connect-to-did-domain'].includes(action)) {
        return false;
      }
    }
    return true;
  }, [action, sessionContext?.session?.user]);

  const autoGenerateSourceAppPid = useCreation(() => {
    if (isUndefined(sourceAppPid)) {
      const federatedEnabled = getFederatedEnabled(blocklet);
      const master = getMaster(blocklet);
      if (federatedEnabled && master?.appPid) {
        return master.appPid;
      }
    }
    return sourceAppPid;
  }, [sourceAppPid, blocklet]);

  const appInfoList = useCreation(() => {
    const appList = getApps(blocklet);

    return appList.filter((x) => {
      if (canSwitchApp) {
        return true;
      }

      if (!isUndefined(sourceAppPid)) {
        return x.sourceAppPid === sourceAppPid;
      }
      if (!isUndefined(connectState.sourceAppPid)) {
        return x.sourceAppPid === connectState.sourceAppPid;
      }
      if (sessionContext?.session?.user) {
        return x.sourceAppPid === sessionContext.session.user.sourceAppPid;
      }
      return x.sourceAppPid === autoGenerateSourceAppPid;
    });
  }, [canSwitchApp, sourceAppPid, connectState.sourceAppPid, autoGenerateSourceAppPid, sessionContext?.session?.user]);

  return { appInfoList, autoGenerateSourceAppPid, canSwitchApp };
}
