import { context } from '@/common/context'; import { rewardsCommands } from '../rewards-command'; import { createEventPromiseHandler } from '../../event-listener'; import { IUseUnloginModalResultEvent, UseUnloginModalResultEventName } from '@/common/rewards/reward-emitter'; import { rewardsEmitter, InvokeUnloginModalEventName } from '@/common/rewards/reward-emitter'; import { sleep } from '@jolibox/common'; import { IHttpClient } from '@/common/http'; import { unlockOptionsHandler } from '../../common'; import { CURRENCY_HANDLERS, CurrencyType } from './currency-handlers'; export const registerUseUnloginCommand = ( prefix: 'JOLI_COIN' | 'ADS-JOLI_COIN' | 'JOLI_GEM' | 'ADS-JOLI_GEM', currency: 'JOLI_COIN' | 'JOLI_GEM', params: { httpClient: IHttpClient; showUnloginModal: (currency: 'JOLI_COIN' | 'JOLI_GEM') => Promise<{ result: 'CANCEL' | 'FAILED' | 'SUCCESS' | 'ADS' | 'NOT_SUPPORT'; rewards?: { isFirstLogin: boolean; claimedRewardValue: number; }; }>; } ) => { const { showUnloginModal, httpClient } = params; rewardsCommands.registerCommand(`Rewards.${prefix}.useUnloginModal`, async () => { const isLogin = context.hostUserInfo?.isLogin; const unlockOptions = await unlockOptionsHandler.getData(); console.log('-----isLogin-----', !!isLogin); if (!isLogin) { const unloginModalResult = await showUnloginModal(currency); console.log('-----unloginModalResult-----', unloginModalResult); if (unloginModalResult.result == 'FAILED' || unloginModalResult.result == 'CANCEL') { return { result: 'FAILED' }; } const { isFirstLogin, claimedRewardValue } = unloginModalResult.rewards ?? {}; if (unloginModalResult.result == 'SUCCESS') { if (isFirstLogin && claimedRewardValue) { await sleep(3000); // wait for center toast to show } //check balance using currency handler const handler = CURRENCY_HANDLERS[currency as CurrencyType]; const newBalance = await handler.fetchBalance(httpClient); const currencyQuantity = handler.getQuantity(unlockOptions); const currentUser = handler.getCurrentUser(unlockOptions); const newUser = handler.createUpdatedUser(newBalance?.balance ?? 0, currentUser.enableAutoDeduct); const updateKey = handler.getUpdateKey(); unlockOptionsHandler.updateData({ [updateKey]: newUser }); if (newUser.balance >= currencyQuantity) { return { result: 'SUCCESS' }; } } } return { result: 'CONTINUE' }; }); }; //EVENTS export const createShowUnloginModal = ( type: 'JOLI_COIN' | 'ADS-JOLI_COIN' | 'JOLI_GEM' | 'ADS-JOLI_GEM', buttons: { confirmButtonText: string; cancelButtonText: string; } ) => { return async (currency: 'JOLI_COIN' | 'JOLI_GEM') => { const modalHandler = createEventPromiseHandler< IUseUnloginModalResultEvent, typeof UseUnloginModalResultEventName >(rewardsEmitter, UseUnloginModalResultEventName); rewardsEmitter.emit(InvokeUnloginModalEventName, type, { confirmButtonText: buttons.confirmButtonText, cancelButtonText: buttons.cancelButtonText, currency }); const modalResult = await modalHandler.getFreshData(); return modalResult; }; };