package com.czg.cashier_reserve.channel;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;

import androidx.annotation.RequiresApi;

import com.czg.cashier_reserve.ContextHolder;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.flutter.Log;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.EventChannel;

public class EventChannelManager {
	public static Map<String, BroadcastReceiver> receiverMap = new HashMap<>();
	public static List<BroadcastReceiver> broadcastReceiverList = new ArrayList<>();

	private static EventChannel callLogChannel;

	public static void addEventChannel(BinaryMessenger messenger) {
		getCallLogCallback(messenger);
	}

	public static void getCallLogCallback(BinaryMessenger messenger) {
		if (messenger == null) {
			return;
		}

		Log.i("EventChannelManager", "getCallLogCallback");

		callLogChannel = new EventChannel(messenger, ChannelNames.getChannelName(ChannelNames.CALL_LOG_CALLBACK));

		callLogChannel.setStreamHandler(new EventChannel.StreamHandler() {
			private BroadcastReceiver broadCast;

			@Override
			public void onListen(Object o, EventChannel.EventSink eventSink) {
				Log.i("EventChannelManager", "onListen");
				broadCast = EventChannelManager.getBroadCast(eventSink);
				Context context = ContextHolder.getInstance().getContext();
				IntentFilter intentFilter = new IntentFilter(EventChannelManager.Action.GET_CALL_LOG_FINISH);
				context.registerReceiver(broadCast, intentFilter);
				receiverMap.put(EventChannelManager.Action.GET_CALL_LOG_FINISH, broadCast);
			}

			@Override
			public void onCancel(Object o) {
				Context context = ContextHolder.getInstance().getContext();
				context.unregisterReceiver(broadCast);
				broadcastReceiverList.remove(broadCast);
				broadCast = null;
			}
		});
	}

	public static BroadcastReceiver getBroadCast(EventChannel.EventSink eventSink) {
		BroadcastReceiver b = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				Log.i("EventChannelManager", "onReceive");
				String action = intent.getAction();
				Log.i("EventChannelManager", "action name == " + action);
				if (Action.GET_CALL_LOG_FINISH.equals(action)) {
					String extra = intent.getStringExtra("callLog");
					eventSink.success(extra);
				} else {
					eventSink.error("没有该事件", null, null);
				}
			}
		};

		broadcastReceiverList.add(b);
		return b;
	}

	// 这里假设Action是一个定义了相关常量的类，示例如下，你可以根据实际情况调整
	public static class Action {
		public static final String GET_CALL_LOG_FINISH = ChannelNames.BASE_NAME + "get_call_log_finish";
	}
}
