package com.yeejoin.equip.eqmx;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yeejoin.equip.kafka.KafkaProducerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class ConnectionManager {

    private final Map<String, Connector> connectors = new ConcurrentHashMap<>();

    @Value("${mqtt.data.type:normal}")
    private String msgType;

    @Value("${kafka.topic}")
    private String kafkaTopic;

    @Autowired
    private KafkaProducerService kafkaProducerService;

    @PostConstruct
    public void initFromDb() {
        List<ConnectionConfigDTO> connectionConfigDTOS = new ArrayList<>();

        ConnectionConfigDTO xz = new ConnectionConfigDTO();
        xz.setId("1");
        xz.setCommunicationType("mqtt");
        xz.setClientId("xiazao");
        xz.setTopics("/farm/xiazao/yitihua");
        xz.setUrl("tcp://kafka-external.ruioutech.com:1883");
        xz.setUsername("test");
        xz.setPassword("test_Zxnk@2025");
        xz.setKafkaTopic(kafkaTopic);
        xz.setKafkaProducerService(kafkaProducerService);
        connectionConfigDTOS.add(xz);

        ConnectionConfigDTO th = new ConnectionConfigDTO();
        th.setId("2");
        th.setCommunicationType("mqtt");
        th.setClientId("taihe");
        th.setTopics("/solar/taihe/yitihua");
        th.setUrl("tcp://kafka-external.ruioutech.com:1883");
        th.setUsername("test");
        th.setPassword("test_Zxnk@2025");
        th.setKafkaTopic(kafkaTopic);
        th.setKafkaProducerService(kafkaProducerService);
        connectionConfigDTOS.add(th);

        connectionConfigDTOS.forEach(cfg -> {
            try {
                cfg.setMsgType(msgType);
                addConnector(cfg);
            } catch (Exception e) {
                log.error("初始化连接失败: {}", JSONObject.toJSONString(cfg), e);
            }
        });
    }

    public void addConnector(ConnectionConfigDTO configDTO) {
        try {
            if (connectors.containsKey(configDTO.getId())) throw new IllegalArgumentException("ID 已存在: " + configDTO.getId());
            Connector conn = new MqttConnector(configDTO);
//                    Connector conn = switch (configDTO.getCommunicationType().toLowerCase()) {
//                case "mqtt" -> new MqttConnector(configDTO);
//                default -> throw new IllegalArgumentException("未知类型: " + configDTO.getCommunicationType());
//            };
            conn.connect();
            connectors.put(configDTO.getId(), conn);
            log.info("{} client {} connect success", configDTO.getCommunicationType().toUpperCase(), configDTO.getName());
        } catch (Exception e){
            log.error("初始化连接失败: {}", JSONObject.toJSONString(configDTO), e);
        }
    }

    public void modifyConnector(ConnectionConfigDTO configDTO) {
        try {
            removeConnector(configDTO.getId());
            addConnector(configDTO);
        } catch (Exception e){
            log.error("修改连接失败: {}", JSONObject.toJSONString(configDTO), e);
        }
    }

    public void removeConnector(String id) throws Exception {
        Connector conn = connectors.remove(id);
        if (conn != null) {
            conn.disconnect();
        }
    }

    public void removeConnector(List<String> ids){
        if(ids!=null&&ids.isEmpty())
        {
            ids.forEach(id -> {
                try {
                    removeConnector(id);
                } catch (Exception e) {
                    log.error("删除连接失败: {}", id, e);
                }
            });
        }
    }

    public Map<String, Connector> getConnectors() {
        return connectors;
    }

    public Connector getConnector(String id) {
        return connectors.get(id);
    }


    public Map<String, Connector> listConnectors() {
        return connectors;
    }

    @PreDestroy
    public void shutdown() {
        connectors.values().forEach(c -> {
            try {
                c.disconnect();
            } catch (Exception ignored) {
            }
        });
    }
}
