#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"
#include "gpio_init.h"

#define PTHREAD_MAX 6

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

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

int g_mqtt_grc=0;

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){    
        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);
    }
    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) {
        // if( g_device_type >= 200 && g_device_type<=205) delay_ms(45);
        // if( g_device_type != 202)delay_ms(100);
        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) {

    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) {
            my_zlog_warn("mqtt fail ...");
            mqtt_clean(mosq);
            mosq = NULL;
            continue;
        }

        g_mqtt_grc = mqtt_cycle(mosq);  // 阻塞直到断开
        if(g_mqtt_grc !=0 ){
            my_zlog_warn("mqtt fail ...");
            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++;//设备计时，坦克打击倒退逻辑

        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_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 < PTHREAD_MAX; i++) {
        if (g_thread[i]) pthread_join(g_thread[i], NULL);
    }
}

