import { getStorageData } from '@/storage/';
import { DeviceEventEmitter } from 'react-native';
import { guid } from '@/utils/';

interface Message {
	info: any;
	data: any;
}
class MessageCenter {
	messageCallbackMap: Map<any, any>;
	messageFailbackMap: Map<any, any>;
	timer: null;
	constructor() {
		this.messageCallbackMap = new Map();
		this.messageFailbackMap = new Map();
		this.timer = null;
	}
	async send(message: Message) {
		console.log('MessageCenter', message);
		const { target, messageId, actionType } = message.info;
		switch (message.info.actionType) {
			case 'IFRAME_GET_EXTENSION_STORGE_DATA':
				const _data = await getStorageData(message.data.key);
				target.postMessage(
					JSON.stringify({
						info: { messageId, actionType },
						data: _data,
					}),
				);
				break;
			case 'IFRAME_TWITTER_API_DO_TASK':
			case 'IFRAME_DO_TASK_LIKE':
			case 'IFRAME_DO_TASK_RETWEET':
				const rnMessageId = `${actionType}-${guid()}`;
				DeviceEventEmitter.emit(actionType, {
					info: {
						rnMessageId: rnMessageId,
					},
					data: message.data,
				});
				DeviceEventEmitter.addListener(rnMessageId, data => {
					target.postMessage(
						JSON.stringify({
							info: { messageId, actionType },
							data: data,
						}),
					);
					// DeviceEventEmitter.removeCurrentListener();
				});
				break;
			default:
				break;
		}
	}
	listen() {}
}

const messageCenter = new MessageCenter();
export default messageCenter;
