#include "device_identity.h"
#include "mqtt_init.h"
#include "delay.h"
#include "device_wifi_change.h"
#include "device_wifi_manager.h"
#include "http_config_mqtt.h"

#define MAX_WIFI_ENTRIES 50
#define SSID_MAX_LENGTH 64

/*成功发送3010，保存wifi和删除WiFi都会发送，wifi_status未0为成功*/
void device_wifi_public_sendmqtt(int wifi_status) { 

    get_current_wifi();
    cJSON *root = cJSON_CreateObject();
    cJSON *body = cJSON_CreateObject();
    cJSON *head = cJSON_CreateObject();

    cJSON_AddNumberToObject(body, "wifi_status", wifi_status);//为0成功

    cJSON_AddNumberToObject(head, "message_type",3010);

    cJSON_AddItemToObject(root, "body", body);
    cJSON_AddItemToObject(root, "head",head);

    char *payload = cJSON_PrintUnformatted(root);
    my_zlog_debug("%s",payload);
    for(int i=0;i<g_mqtt_cam_config_t->mqtt_count;i++){
        mosquitto_publish(g_clients_t[i].mosq, NULL, mqtt_topic_pure_number(), strlen(payload), payload, 0, false); 
    } 
    
    cJSON_Delete(root);  // 释放 cJSON 对象
}


/*接收到删除的mqtt消息*/
void device_wifi_rec_delete(cJSON *body){
    cJSON *wifi_ssid = cJSON_GetObjectItem(body, "wifi_ssid");
    cJSON *wifi_password = cJSON_GetObjectItem(body, "wifi_password");
    cJSON *wifi_status = cJSON_GetObjectItem(body, "wifi_status");
    if(cJSON_IsString(wifi_ssid)  && cJSON_IsString(wifi_password)){
        char *ssid = wifi_ssid->valuestring,*password=wifi_password->valuestring;
        int wifi_statustemp = wifi_status->valueint;
        if(delete_wifi_by_ssid(ssid)==0){
            my_zlog_info("删除成功");
            device_wifi_public_sendmqtt(1);
        }else {
            my_zlog_info("删除失败");
        }
    }
}

/*进行保存wifi*/
int orange_pi_save_wifi(const char* ssid, const char* password) {
    // 参数检查
    if (!ssid || !password || strlen(ssid) == 0 || strlen(password) == 0) {
        fprintf(stderr, "[ERROR] SSID或密码为空\n");
        return -1;
    }

    // 安全检查（防止命令注入）
    if (strpbrk(ssid, "\"`$|") || strpbrk(password, "\"`$|")) {
        fprintf(stderr, "[ERROR] 检测到非法字符\n");
        return -1;
    }

    // 写入NetworkManager标准配置文件
    char cmd[256];
    snprintf(cmd, sizeof(cmd),
        "nmcli connection add type wifi con-name \"%s\" ifname wlan0 ssid \"%s\" -- \n"
        "nmcli connection modify \"%s\" wifi-sec.key-mgmt wpa-psk wifi-sec.psk \"%s\" \n"
        "chmod 600 /etc/NetworkManager/system-connections/%s.nmconnection",
        ssid, ssid, ssid, password, ssid);

    if (system(cmd) != 0) {
        my_zlog_error("[ERROR] 保存配置失败");
        return -1;
    }

    my_zlog_info("[SUCCESS] 已保存WiFi配置: %s", ssid);
    return 0;
}


/*保存WiFi接口，接收到mqtt消息进行保存*/
void device_wifi_rec_sava(cJSON *body){
    cJSON *wifi_ssid = cJSON_GetObjectItem(body, "wifi_ssid");
    cJSON *wifi_password = cJSON_GetObjectItem(body, "wifi_password");
    cJSON *wifi_status = cJSON_GetObjectItem(body, "wifi_status");
    if(cJSON_IsString(wifi_ssid)  && cJSON_IsString(wifi_password)){
        char *ssid = wifi_ssid->valuestring,*password=wifi_password->valuestring;
        int wifi_statustemp = wifi_status->valueint;
        my_zlog_debug("接收到保存WiFi名称和密码");
        orange_pi_save_wifi(ssid,password);
        device_wifi_public_sendmqtt(0);
    }
}



/**
 * @brief 获取系统保存的所有WiFi配置名称
 * @param ssid_list 用于存储SSID的数组
 * @param max_count 数组最大容量
 * @return 实际获取到的SSID数量，-1表示失败
 */
int get_saved_wifi_list(char ssid_list[][SSID_MAX_LENGTH], int max_count) {
    const char *nm_conn_dir = "/etc/NetworkManager/system-connections/";
    DIR *dir;
    struct dirent *entry;
    int count = 0;

    // 打开NetworkManager配置目录
    if ((dir = opendir(nm_conn_dir)) == NULL) {
        my_zlog_error("无法打开NetworkManager配置目录");
        return -1;
    }

    // 遍历目录中的文件
    while ((entry = readdir(dir)) != NULL && count < max_count) {
        // 跳过.和..以及非普通文件
        if (entry->d_type != DT_REG) continue;

        // 检查文件扩展名（可选）
        char *dot = strrchr(entry->d_name, '.');
        if (dot && strcmp(dot, ".nmconnection") == 0) {
            // 去除.nmconnection后缀
            strncpy(ssid_list[count], entry->d_name, dot - entry->d_name);
            ssid_list[count][dot - entry->d_name] = '\0';
        } else {
            // 直接使用文件名作为SSID
            strncpy(ssid_list[count], entry->d_name, SSID_MAX_LENGTH - 1);
            ssid_list[count][SSID_MAX_LENGTH - 1] = '\0';
        }
        count++;
    }

    closedir(dir);
    return count;
}


/**
 * @brief 打印所有已保存的WiFi配置
 */
void device_send_saved_wifi(){
    get_current_wifi();

    char list_wifi[MAX_WIFI_ENTRIES][SSID_MAX_LENGTH];
    int count = get_saved_wifi_list(list_wifi, MAX_WIFI_ENTRIES);

    if (count <= 0) {
        my_zlog_debug("未找到保存的WiFi配置");
        return;
    }

    cJSON *root = cJSON_CreateObject();
    cJSON *body = cJSON_CreateObject();
    cJSON *head = cJSON_CreateObject();
    cJSON_AddStringToObject(body, "current_connected", g_current_ssid[0] ? g_current_ssid : "");
    cJSON *array = cJSON_CreateArray();
     for (int i = 0; i < count; i++) {
        cJSON *item = cJSON_CreateObject();
        my_zlog_debug("%d. %s\n", i+1, list_wifi[i]);
        cJSON_AddStringToObject(item, "ssid", list_wifi[i]);
        cJSON_AddItemToArray(array, item);
    }
    cJSON_AddItemToObject(body, "available_wifi", array);
    cJSON_AddNumberToObject(head, "message_type", 3012);
    cJSON_AddItemToObject(root, "body", body);
    cJSON_AddItemToObject(root, "head",head);

    char *json_str = cJSON_Print(root);
    if (json_str) {
        my_zlog_debug("%s", json_str);

    for(int i=0;i<g_mqtt_cam_config_t->mqtt_count;i++){
        mosquitto_publish(g_clients_t[i].mosq, NULL, mqtt_topic_pure_number(), strlen(json_str), json_str, 0, false); 
    } 

        free(json_str);
    }
    cJSON_Delete(root);
}