#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
#include "thread_monitor.h"
#include "bmser_log.h"

#define MAX_THREADS            10  // 假设最多处理的线程数量
#define MAX_ROUTINE_NAME_LEN   64


typedef struct thread_info_t {
    pthread_t thread_id;
    int monitor_index;
    thread_start_routine_cb start_routine; // 原始的start_routine函数
    thread_destructor_cb destructor;       // 析构函数
    char routine_name[64];
    void* arg; // 原始start_routine的参数
    bool need_running;
    bool is_running;
} thread_info_t;

thread_info_t thread_registry[MAX_THREADS] = {0};
pthread_mutex_t registry_mutex = PTHREAD_MUTEX_INITIALIZER;

void* threadWrapper(void* arg) {
    thread_info_t* thread_info = (thread_info_t*)arg;
    
    // 调用原始的start_routine函数
    thread_info->start_routine(&thread_info->need_running,thread_info->arg);
    // 线程即将退出前调用析构函数
    if (thread_info->destructor) {
        thread_info->destructor();
    }
    // 更新状态
    pthread_mutex_lock(&registry_mutex);
    thread_info->is_running = false;
    pthread_mutex_unlock(&registry_mutex);
    if(thread_info->need_running){
        dy_syslog(LOG_ERR, "Thread %s exited, will restart\n",thread_info->routine_name);
    }
    else{
        dy_syslog(LOG_ERR, "Thread %s exited\n",thread_info->routine_name);
    }
    return NULL;
}

int threads_monitor_register_thread(thread_start_routine_cb start_routine, thread_destructor_cb destructor, const char* routine_name, void* arg) {
    int i = 0, res = 0;
    
    pthread_mutex_lock(&registry_mutex);
    for (i = 0; i < MAX_THREADS; ++i) {
        if (!thread_registry[i].need_running) {
            thread_registry[i].start_routine = start_routine;
            thread_registry[i].destructor = destructor;
            thread_registry[i].arg = arg;  // 保存传递给原始start_routine的参数
            res = pthread_create(&thread_registry[i].thread_id, NULL, threadWrapper, &thread_registry[i]);
            if(routine_name){
               strncpy(thread_registry[i].routine_name, routine_name, (MAX_ROUTINE_NAME_LEN - 1));
            }
            if (res == 0) {
                pthread_detach(thread_registry[i].thread_id);
                thread_registry[i].need_running = true;
                thread_registry[i].is_running = true;
                thread_registry[i].monitor_index = i;
            }
            break;
        }
    }
    pthread_mutex_unlock(&registry_mutex);
    
    return res;
}

int threads_monitor_runnable() {
    pthread_mutex_lock(&registry_mutex);
    for (int i = 0; i < MAX_THREADS; ++i) {
        if (thread_registry[i].need_running && !thread_registry[i].is_running) {
            // 重启线程
            pthread_create(&thread_registry[i].thread_id, NULL, threadWrapper, &thread_registry[i]);
            thread_registry[i].is_running = true;
            pthread_detach(thread_registry[i].thread_id);
        }
    }
    pthread_mutex_unlock(&registry_mutex);
    return 0;
}

int threads_monitor_stop_all()
{
    uint32_t wait_count = 0;
    for (int i = 0; i < MAX_THREADS; ++i) {
        if (thread_registry[i].need_running && thread_registry[i].is_running) {
            wait_count = 0;
            // 取消运行
            pthread_mutex_lock(&registry_mutex);
            thread_registry[i].need_running = false;
            pthread_mutex_unlock(&registry_mutex);
            //TODO: 这里的超时等待就先简单实现，后面可以考虑优化
            while(thread_registry[i].is_running){
                usleep(10000);
                if(++wait_count > 1000){
                    dy_syslog(LOG_ERR, "Thread %s stop failed, wait =%llu ms\n",thread_registry[i].routine_name,(wait_count*10));
                    break;
                }
            }
        }
    }
    
}