#include "common.h"
#include "delay.h"
#include "pthread_open.h"
#include "mqtt_init.h"
#include "mqtt_infor_handle.h"
#include "browser_open.h"
#include "mqtt_verify.h"
#include "device_wifi_change.h"
#include "devcontrol_common.h"
#include "browser_open.h"
#include "device_init.h"
#include "audioplay.h"

pthread_t g_thread[6];  // 全局线程句柄数组（或传参）

int g_webrtc_index=0;

int g_mqtt_grc=0;

void* g_args[6] = { NULL, NULL, NULL, NULL, NULL, NULL };

int thread_start_init(ThreadFunc thread_exit_time, ThreadFunc thread_mqtt_beat,
                 ThreadFunc thread_open_browser, ThreadFunc thread_mqtt_reconnect,
                 ThreadFunc thread_time_calculation, ThreadFunc thread_play_mp3) {
    
    ThreadFunc thread_funcs[] = {
        thread_exit_time,
        thread_mqtt_beat,
        thread_open_browser,
        thread_mqtt_reconnect,
        thread_time_calculation,
        thread_play_mp3
    };

    for (int i = 0; i < 6; i++) {
        if (pthread_create(&g_thread[i], NULL, thread_funcs[i], g_args[i]) != 0) {
            my_zlog_error("创建线程 %d 失败", i);
            return i + 1;
        }
    }
    return 0;
}


//出现意外自动停止
void *thread_exit_time(void *arg) { 
    while(1){    
        delay_ms(100);
        g_devcontrol_exit_count++;
        if(g_devcontrol_exit_count>=5) {
        device_stop(g_device_type);
        g_devcontrol_exit_count=6;
        } 
    }
    return NULL; 
}

void *thread_mqtt_beat(void *arg) { 
    my_zlog_info("thread_mqtt_beat start");
    delay_s(5);
    g_webrtc_index=1;
    /*在这步进行检测，等mqtt连接成功后检查*/
    if(wifi_change_sendmqtt_init()!=0){
      my_zlog_error("WIFI是否更改检查相关，不会到这一步，有问题会直接重启，可能会导致重启，不会因此造成程序停止");
   }
    while(1) {
        if( g_device_type == 202) delay_ms(45);
        if( g_device_type != 202)delay_ms(100);
        g_heartbeat_count++;
        if(g_mqtt_grc == 0){
            
            mqtt_beat_wirte();//心跳，3s一个   
        }   
    }
    return NULL;
}

void *thread_open_browser(void *arg) { 
    while(1){
        if(g_webrtc_index==1) {
            my_zlog_info("open cam");
            opencamsh();//10s后打开游览器并且进入网址 
        }
        delay_ms(200);
    }
    
    return NULL; 
}

//mqtt异常处理，断开自动重连，简单粗暴
void *thread_mqtt_reconnect(void *arg) {
    if (mqtt_init() != 0) {
        my_zlog_fatal("mqtt_init failed");
        return NULL;
    }
    while (1) {
        if (mosq == NULL) {
            mqtt_init();
            if (!mosq) {
                mqtt_clean(mosq);
                my_zlog_error("Failed to create mosquitto client");
                continue;
            }
        }

        g_mqtt_grc = mqtt_create(mosq);
        if (g_mqtt_grc != 0) {
            mqtt_clean(mosq);
            mosq = NULL;
            continue;
        }

        g_mqtt_grc = mqtt_cycle(mosq);  // 阻塞直到断开
        if(g_mqtt_grc !=0 ){
            mqtt_clean(mosq);
            mosq = NULL;
        }
        my_zlog_warn("mqtt disconnected ...");
    }
    mqtt_clean(mosq);
    return NULL;
}

//专门用于计时的线程
void *thread_time_calculation(void *arg) {
     while (1) {
         delay_ms(5);
        g_device_delay_count++;//设备计时，坦克打击倒退逻辑
        g_verify_count++;//验证计时,每15s一次
        if(g_verify_count >= 20000) g_verify_count = 20000;
        if(g_device_delay_count >= 5000) g_device_delay_count = 5000;
     }
    return NULL;
}

//专门处理MP3播放
void *thread_play_mp3(void* arg) {
    audioplay_cycle();
    return NULL;
}

// 等待线程结束
void thread_end_close() {
    for (int i = 0; i < 6; i++) {
        if (g_thread[i]) pthread_join(g_thread[i], NULL);
    }
}

