package com.njzscloud.common.localizer.jt808.support;

import com.njzscloud.common.localizer.DeviceStore;
import com.njzscloud.common.localizer.Localizer;
import com.njzscloud.common.localizer.contant.LocalizerType;
import com.njzscloud.common.localizer.contant.MessageType;
import com.njzscloud.common.localizer.jt808.message.JT808Message;
import com.njzscloud.common.localizer.jt808.message.TerminalMessageBody;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

/**
 * 消息中心
 */
@Slf4j
public class JT808MessageCenter {
    private static final Map<LocalizerType, Map<MessageType, Consumer<TerminalMessageBody>>> listeners = new ConcurrentHashMap<>();

    public static void dispatch(JT808Message message) {
        int messageId = message.getMessageId();
        String terminalId = message.getTerminalPhone();
        Localizer localizer = DeviceStore.determineLocalizer(terminalId);
        if (localizer == null) {
            log.error("未找到设备：{}", terminalId);
            return;
        }
        LocalizerType localizerType = localizer.getLocalizerType();

        Map<MessageType, Consumer<TerminalMessageBody>> m = listeners.computeIfPresent(localizerType, (k, v) -> {
            MessageType messageType = MessageType.getMessageType(messageId);
            if (messageType == MessageType.TerminalLocationBatchReport) {
                log.info("批量上报：{}", message);
            }

            if (messageType == null) {
                log.error("未找到消息类型，设备号：{}，消息 Id：0x{}", terminalId, Integer.toHexString(messageId));
                return v;
            }
            Consumer<TerminalMessageBody> c = v.computeIfPresent(messageType, (k1, v1) -> {
                try {
                    v1.accept(new TerminalMessageBody(message));
                } catch (Exception e) {
                    log.error("消息处理异常：设备号：{}，设备类型：{}，消息类型：{}", terminalId, localizerType, messageType, e);
                }
                return v1;
            });
            if (c == null) {
                log.error("消息处理器不存在，设备号：{}，设备类型：{}，消息类型：{}", terminalId, localizerType, messageType);
            }
            return v;
        });
        if (m == null) {
            log.error("设备处理器不存在，设备号：{}，设备类型：{}", terminalId, localizerType);
        }
    }

    public static void addListener(LocalizerType localizerType, MessageType messageType, Consumer<TerminalMessageBody> listener) {
        listeners.computeIfAbsent(localizerType, k -> new ConcurrentHashMap<>()).put(messageType, listener);
    }

    public static void addListeners(LocalizerType localizerType, Map<MessageType, Consumer<TerminalMessageBody>> listeners) {
        listeners.forEach((messageType, consumer) -> addListener(localizerType, messageType, consumer));
    }
}
