#include "common.h"
#include "audioplay.h"
#include "device_identity.h"
#include "mqtt_init.h"
#include "http_config_mqtt.h"

int audio_status=7;
char urlbuf[512];
char keybuf[256];
double audio_volume=0.8;

int audio_wheat_init();

//接收音频播放
void audioplay_mqtt_receive(cJSON *json) {
    // 解析"audioLink"字段（修正了原始JSON中的拼写错误）
    cJSON *audio_link = cJSON_GetObjectItemCaseSensitive(json, "audioLink");
    if (cJSON_IsString(audio_link) && (audio_link->valuestring != NULL)) {
        my_zlog_debug("音频链接: %s", audio_link->valuestring);
        char *url=audio_link->valuestring;
        snprintf(urlbuf, sizeof(urlbuf), "%s", url);
    } else {
        my_zlog_warn("错误：无法解析音频链接字段");
    }

    // 解析"key"字段
    cJSON *key_char = cJSON_GetObjectItemCaseSensitive(json, "key");
    if (cJSON_IsString(key_char) && (key_char->valuestring != NULL)) {
        my_zlog_debug("音频链接: %s", key_char->valuestring);
        char *key=key_char->valuestring;
        snprintf(keybuf, sizeof(keybuf), "%s", key);
    } else {
        my_zlog_warn("错误：无法解析音频链接");
        audio_status=5;
    }

    // 解析"status"字段
    cJSON *audio_status_val = cJSON_GetObjectItemCaseSensitive(json, "status");
    if (cJSON_IsNumber(audio_status_val)) {
        my_zlog_debug("标志: %d", audio_status_val->valueint);
        audio_status=audio_status_val->valueint;
    } else {
        my_zlog_warn("错误：无法解析标志字段");
    }

    // 解析"volume"字段
    cJSON *volume = cJSON_GetObjectItemCaseSensitive(json, "volume");
    if (cJSON_IsNumber(volume)) {
        my_zlog_debug("声量大小: %1f", volume->valuedouble);
        audio_volume=volume->valuedouble + 0.0;
    } else {
        my_zlog_warn("错误：无法解析声量字段");
    }
}  

//发送音频播放是否完毕
void  audioplay_send_mqtt() {
    cJSON *root = cJSON_CreateObject();
    cJSON *body = cJSON_CreateObject();
    cJSON *head = cJSON_CreateObject();
        // 添加各个字段到 JSON 对象
    cJSON_AddStringToObject(body, "type", "audio");
    cJSON_AddStringToObject(body, "audioLink", urlbuf);
    cJSON_AddStringToObject(body, "key", keybuf);
    cJSON_AddNumberToObject(body, "status", audio_status);
    cJSON_AddNumberToObject(body, "volume", audio_volume);

    cJSON_AddNumberToObject(head, "message_type",3001);

    cJSON_AddItemToObject(root, "body", body);
    cJSON_AddItemToObject(root, "head",head);
    // 将 JSON 对象转换为字符串
    char* json_string = cJSON_PrintUnformatted(root);
    my_zlog_debug("%s",json_string);

    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_string), json_string, 0, false); 
        } 
    // 释放 JSON 对象内存
    cJSON_Delete(root);
}

//音频播放
void audioplay_cycle(){
    char command[1024];
    int ret;
    while(1){
        if(audio_status==0){

            char *urlmoddle=urlbuf;
            snprintf(command, sizeof(command),
            "sudo ffplay -nodisp -autoexit -loglevel quiet -af \"volume=%1f\" \"%s\"",
            audio_volume,urlmoddle);

            my_zlog_debug("播放地址: %s\n", urlbuf);
            ret = system(command);
            if (ret == -1) {
                my_zlog_error("播放失败");
                audio_status=2;
            }

            if (WIFEXITED(ret) && WEXITSTATUS(ret) == 0) {
                my_zlog_debug("播放已成功完成 : %s ", urlbuf);  
                audio_status=1;   
            } else {
                my_zlog_warn("播放失败或中断: %s ", urlbuf);
                audio_status=2;
            }
        audioplay_send_mqtt();
        }

        video_tts_play();

        delay_us(500);
    
    }
}

int audio_wheat_init(){
    int adino_jude = system("pactl load-module module-alsa-sink device=hw:2,0");
    if(adino_jude  == 0 ){
        my_zlog_debug("命令执行成功！");
        return 0;
    }else {
        if(adino_jude  != 0) my_zlog_warn("喇叭命令执行失败，返回状态码: %d", adino_jude );
        return -1;
    }
}

int audio_speaker_init() {

    int adino_play_jude =system("pactl load-module module-alsa-source device=hw:2,0");
    
    if ( adino_play_jude==0 ) {
        my_zlog_debug("命令执行成功！");
        return 0;
    } else {
        if(adino_play_jude!=0) my_zlog_warn("麦命令执行失败，返回状态码: %d", adino_play_jude );
        return -1;
    }
}

int audio_init(){
    delay_s(60);
    audio_wheat_init();
    delay_s(3);
    audio_speaker_init();

    return 0;
}