#include "common.h"
#include "mqtt_verify.h"
#include "mqtt_init.h"
#include "device_identity.h"
#include "mqtt_infor_handle.h"
#include "http_config_mqtt.h"

mqttclient g_clients_t[MAX_SERVERS];

char g_uuid_mqtt_topic_id[MAX_SERVERS][56];
// struct mosquitto *mosq;

int add_mqtt_create(const char *host, int port, int clients_count);

//mqtt初始化
int mqtt_init() {

    mosquitto_lib_init();
    // 这里创建mosq可以保留，也可以删除这一行，让创建放到 Mqtt_onnect 里
    for(int i=0;i<g_mqtt_cam_config_t->mqtt_count;i++){
      int erg= add_mqtt_create(g_mqtt_cam_config_t->mqtt_servers[i],BROKER_PORT,i);
            if(erg !=0){
                return -1;
            }
    } 

    if (!g_clients_t) {
        my_zlog_error("Failed to create Mosquitto client");
        return -1;
    }
    return 0;
}

//回调函数
void on_connect(struct mosquitto *mosq, void *obj, int rc) {

    mqttclient *client_t = (mqttclient*)obj;

    if (rc == 0) {
        my_zlog_info("Connected to broker");
        my_zlog_info("[Connected] %s:%d (%s)",
               client_t->host, client_t->port, client_t->client_id);

        mosquitto_subscribe(mosq, NULL, mqtt_topic_app2dev_number(), 0);
        mosquitto_subscribe(mosq, NULL, mqtt_topic_ser2dev_number(), 0);
    } else {
        fprintf(stderr, "Connection failed with code %d\n", rc);
        my_zlog_fatal("[Connection Failed] %s:%d rc=%d",
               client_t->host, client_t->port, rc);
    }
}


//消息回环函数  
void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) {

     mqttclient *client_t = (mqttclient*)obj;

     my_zlog_info("[Message from %s:%d] topic=%s payload=%s",
           client_t->host, client_t->port,
           message->topic, (char*)message->payload);

    // 确保消息有效
    if (message->payload && message->payloadlen) { // 将消息内容转换为字符串
        char *payload_str = (char *)malloc(message->payloadlen + 1);
        if (!payload_str) {
            return;
        } 

        memcpy(payload_str, message->payload, message->payloadlen);
        payload_str[message->payloadlen] = '\0';

        // 解析 JSON
        cJSON *json = cJSON_Parse(payload_str);
        if(json != NULL){
            if(device_message_receive(json)==0) my_zlog_info("进入设备接收mqtt");
        }                     
        
        // 释放 payload 字符串
        free(payload_str); 
        cJSON_Delete(json); 
    }
}

int add_mqtt_create(const char *host, int port, int clients_count){
    static int uuid_index =0;

    if(clients_count >= MAX_SERVERS) {
        my_zlog_error("Max server limit reached.");
        return -1;
    }
    mqttclient *client_t = &g_clients_t[clients_count];
    strncpy(client_t->host, host, sizeof(client_t->host)-1);
    client_t->port = port;

    uuid_t uuid;
    uuid_generate_time(uuid); // 获取UUIDv1

    unsigned short time_part = (uuid[0] << 8) | uuid[1];
    unsigned short mac_part  = (uuid[10] << 8) | uuid[11];
    
    // 组合成32位值（8字符十六进制）
    snprintf(g_uuid_mqtt_topic_id[uuid_index], 9, "%04x%04x", time_part, mac_part);

    client_t->mosq = mosquitto_new(g_uuid_mqtt_topic_id[uuid_index], true, client_t);
    
    uuid_index++;

    if(!client_t->mosq) {
        my_zlog_error("mosquitto_new failed");
        return -1;
    }

    mosquitto_int_option(client_t->mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5);

    mosquitto_reconnect_delay_set(client_t->mosq, 2, 10, true);
    mosquitto_connect_callback_set(client_t->mosq, on_connect);
    mosquitto_message_callback_set(client_t->mosq, on_message);

    mosquitto_username_pw_set(client_t->mosq, USERNAME, PASSWORD);
   
    int rc = mosquitto_connect_async(client_t->mosq, host, port, 60);
    if( rc != MOSQ_ERR_SUCCESS) {
        my_zlog_error("mosquitto_connect failed");
        my_zlog_warn("Failed to connect to broker: %s", mosquitto_strerror(rc));
    
        return -1;
    }

    my_zlog_info("add %s mqttserver success",host);
    return 0;
}

//mqtt清理
void mqtt_clean(){
      // 清理
    for(int i=0;i<g_mqtt_cam_config_t->mqtt_count;i++){
         mosquitto_disconnect(g_clients_t[i].mosq); 
        mosquitto_destroy(g_clients_t[i].mosq);
    }
    
    mosquitto_lib_cleanup();
    my_zlog_notice("清理成功");
}

int mqtt_cycle() {//非阻塞型
    while (1) {
        for(int i=0;i<g_mqtt_cam_config_t->mqtt_count;i++){
          int rc=  mosquitto_loop(g_clients_t[i].mosq, 17, 1);  // 每秒检查一次
          if(rc != MOSQ_ERR_SUCCESS){
             my_zlog_warn("服务器 %s:%d 断开，尝试重连...",
                        g_clients_t[i].host, g_clients_t[i].port);
            mosquitto_reconnect(g_clients_t[i].mosq);
          }
        }
        delay_us(50);
    }

    return 0;
}

