#include "browser_open.h"
#include "device_fileopen.h"
#include "device_identity.h"
#include "http_config_mqtt.h"

char gwebcam[2048];//存放启动火狐网站命令

int  opencamsh() {
    
    char urls[512];

    sprintf(urls,"%s%s",g_mqtt_cam_config_t->videourl,mqtt_topic_pure_number());

    //setenv("DISPLAY", ":0", 1);//设置环境变量https://jywy.yd-ss.com?dev=controcar0004 --new-window sudo 
    sprintf(gwebcam,"su - orangepi -c \"chromium-browser --use-fake-ui-for-media-stream %s\"",urls);
    if(system(gwebcam)!=0){
        my_zlog_error("start fail");
    }
    my_zlog_debug("%s",gwebcam);
    my_zlog_debug("open cam");
    return 0;
}


void refresh_cam() {//刷新页面

    setenv("XAUTHORITY", "/home/orangepi/.Xauthority", 1);//加入授权

    const char *search_command = "xdotool search --class \"chromium-browser\"";//获取窗口id

    FILE *fp = popen(search_command, "r");

    if (!fp) {
        perror("Failed to execute search command");
        return;
    }

    char window_id[32];

    while (fgets(window_id, sizeof(window_id), fp) != NULL) {
        window_id[strcspn(window_id, "\n")] = '\0';
        
        char activate_command[128];

        snprintf(activate_command, sizeof(activate_command), "xdotool windowactivate --sync %s key Ctrl+r", window_id);
        
        pid_t pid = fork();

        if (pid == 0) {
            // 子进程执行命令
            execl("/bin/sh", "sh", "-c", activate_command, (char *)NULL);
            perror("Failed to execute command");
            exit(EXIT_FAILURE);
        } else if (pid > 0) {
            // 父进程不等待子进程结束，继续执行
            printf("Executing in child process: %s\n", activate_command);
        } else {
            perror("Failed to fork");
        }
    }

    pclose(fp);
    //printf("recam\n");
    my_zlog_debug("刷新成功");
}

// 检查Chromium进程是否已运行
bool is_browser_running() {
    FILE *fp = popen("pgrep chromium", "r");
    if (fp == NULL) return false;
    
    char buf[16];
    bool running = (fgets(buf, sizeof(buf), fp) != NULL);
    pclose(fp);
    return running;
}