#include "common.h"
#include "app_device_common.h"
#include "drivers_common.h"
#include "modules_common.h"
#include "pthread_open.h"

#define PTHREAD_MAX 6

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

int g_webrtc_index=0;//判断游览器是否打开

int g_mqtt_grc=0;//mqtt连接状态机

void* g_args[PTHREAD_MAX] = { 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 < PTHREAD_MAX; 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){  
     if(get_self_control_index()==false){
        delay_ms(100);
       
        pthread_mutex_lock(&g_exit_count_mutex);
        g_devcontrol_exit_count++;
        if(g_devcontrol_exit_count>=5) {
        device_stop(g_device_type);
        g_devcontrol_exit_count=6;
        } 
        pthread_mutex_unlock(&g_exit_count_mutex);
     }else {
        set_self_control_time_countfuntion();
        delay_ms(20);
     }  
        
    }
    return NULL; 
}

/*心跳线程处理函数，心跳发送前会像上层请求是否需要验证*/
void *thread_mqtt_beat(void *arg) { 
    my_zlog_info("thread_mqtt_beat start");
    g_webrtc_index=1;
    delay_s(3);
    /*在这步进行检测，等mqtt连接成功后检查*/
    //     if(wifi_change_sendmqtt_init()!=0){
    //       my_zlog_error("WIFI是否更改检查相关，不会到这一步，有问题会直接重启，可能会导致重启，不会因此造成程序停止");
    //    }
    if(verify_open_index_init() !=0){
        my_zlog_info("mqtt send verify is NULL");
    }

    //如果为相关的不需要心跳或者游览器设备，提早结束线程
    if(g_device_type==DEVICE_ROBOT_DOG0501){
         my_zlog_info("device am robot and no c/c++");
        return NULL;
    }

    while(1) {
        delay_ms(100);

        g_heartbeat_count++;
        if(g_mqtt_grc == 0){
            mqtt_beat_wirte();//心跳，3s一个   
        }   
    }
    return NULL;
}

//打开游览器线程，让游览器一直在一个线程中打开并运行
void *thread_open_browser(void *arg) { 

    //如果为相关的不需要心跳或者游览器设备，提早结束线程
    if(g_device_type==DEVICE_ROBOT_DOG0501){
        my_zlog_info("device am robot and no c/c++");
        return NULL;
    }

    system("pkill  chromium");
    delay_s(5);
    while(1){
        if(g_webrtc_index==1) {
            if(is_browser_running() == true ) {
                continue;
            }else{
                my_zlog_info("open cam");
                opencamsh();//10s后打开游览器并且进入网址 
            }
            
        }
        delay_ms(200);
    }
    
    return NULL; 
}

//mqtt异常处理，断开自动重连，简单粗暴
void *thread_mqtt_reconnect(void *arg) {
 
    while(1){
        static int reconnect_count=0;
        static int remqtt_index;
        remqtt_index=mqtt_init();
        if(remqtt_index == 0){
            my_zlog_warn("mqtt success",remqtt_index);
            break;
        }else {
            my_zlog_warn("wait... mqtt reconect,error:%d",remqtt_index);
            delay_ms(300);
            reconnect_count++;
            if(reconnect_count>MAX_RECONNECT_ATTEMPTS){
                send_fail_mqtt_conect();
                break;
            }
            continue;
        }
    }

    mqtt_cycle();
 
    mqtt_clean();
    return NULL;
}

//专门用于计时的线程
void *thread_time_calculation(void *arg) {
     while (1) {
        delay_ms(5);
        g_device_delay_back_count ++;//设备计时，坦克打击倒退逻辑

        pthread_mutex_lock(&g_verify_mutex);
        g_verify_count++;//验证计时,每15s一次
        pthread_mutex_unlock(&g_verify_mutex);

        if(g_verify_count >= 20000) {//防止溢出
            pthread_mutex_lock(&g_verify_mutex);
            g_verify_count = 20000;
            pthread_mutex_unlock(&g_verify_mutex);   
        }
        if(g_device_delay_back_count  >= 5000) g_device_delay_back_count  = 5000;//防止溢出
     }
    return NULL;
}

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

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

