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

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

int opencamsh_china(){
    const char* url = "https://jywy.yd-ss.com?dev=";
    char urls[50];

    sprintf(urls,"%s%s",url,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);
    system(gwebcam);
    my_zlog_debug("%s",gwebcam);
    my_zlog_debug("open cam");
    return 0;
    
}

int opencamsh_abroad(){
    const char* url = "https://video.luckycar.top/?dev=";
    char urls[50];

    sprintf(urls,"%s%s",url,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);
    system(gwebcam);
    my_zlog_debug("%s",gwebcam);
    my_zlog_debug("open cam");
    return 0;
    
}

int  opencamsh() {
    #if BROWSER_MODE == 1
        // 当MODE为1时的代码
        my_zlog_info("Mode 1: 执行代码A");
        return opencamsh_china();
    #elif BROWSER_MODE == 2
        // 当MODE为2时的代码
        my_zlog_info("Mode 2: 执行代码B");
        return opencamsh_abroad();
    #else
        my_zlog_error("未知的 WARM_MODE: %d", BROWSER_MODE);
        return -1;
    #endif
}


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("刷新成功");
}

