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

static char s_webcam[2048];//存放启动火狐网站命令
static int s_open_cam_enter_count = 0;      // 记录 opencamsh 进入次数
static int s_open_cam_fail_streak = 0;      // 连续启动失败次数
static int s_refresh_cam_enter_count = 0;   // 记录 refresh_cam 进入次数
static int s_refresh_cam_fail_count = 0;    // 刷新失败累计次数

int  opencamsh() {
    char urls[512];
    int cmd_ret = 0;

    s_open_cam_enter_count++;
    my_zlog_info("opencamsh enter count:%d", s_open_cam_enter_count);

    snprintf(urls, sizeof(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 
    snprintf(s_webcam, sizeof(s_webcam), "su - orangepi -c \"chromium-browser --use-fake-ui-for-media-stream %s\"", urls);
    cmd_ret = system(s_webcam);
    if (cmd_ret != 0) {
        s_open_cam_fail_streak++;
        if (s_open_cam_fail_streak >= 10 && (s_open_cam_fail_streak % 10) == 0) {
            my_zlog_error("chromium start fail, ret:%d, continuous fail:%d, enter count:%d",
                          cmd_ret, s_open_cam_fail_streak, s_open_cam_enter_count);
        } else {
            my_zlog_warn("chromium start fail, ret:%d, continuous fail:%d, enter count:%d",
                         cmd_ret, s_open_cam_fail_streak, s_open_cam_enter_count);
        }
    } else {
        if (s_open_cam_fail_streak > 0) {
            my_zlog_info("chromium start recovered, previous continuous fail:%d", s_open_cam_fail_streak);
        }
        s_open_cam_fail_streak = 0;
    }
    my_zlog_debug("%s",s_webcam);
    my_zlog_debug("open cam");
    return 0;
}


void refresh_cam() {//刷新页面
    int refreshed_windows = 0;
    int failed_windows = 0;

    s_refresh_cam_enter_count++;
    my_zlog_info("refresh_cam enter count:%d", s_refresh_cam_enter_count);

    setenv("DISPLAY", ":0", 1); // 确保 xdotool 在图形会话中执行
    setenv("XAUTHORITY", "/home/orangepi/.Xauthority", 1);//加入授权

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

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

    if (!fp) {
        s_refresh_cam_fail_count++;
        my_zlog_error("refresh_cam popen fail, total fail:%d", s_refresh_cam_fail_count);
        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 %s key Ctrl+r", window_id);

        if (system(activate_command) == 0) {
            refreshed_windows++;
        } else {
            failed_windows++;
            my_zlog_warn("refresh_cam command fail, window id:%s", window_id);
        }
    }

    pclose(fp);

    if (refreshed_windows == 0) {
        s_refresh_cam_fail_count++;
        my_zlog_warn("refresh_cam no chromium window, total fail:%d, enter count:%d",
                     s_refresh_cam_fail_count, s_refresh_cam_enter_count);
        return;
    }

    if (failed_windows > 0) {
        s_refresh_cam_fail_count++;
        my_zlog_warn("refresh_cam partial fail, success:%d fail:%d total fail:%d",
                     refreshed_windows, failed_windows, s_refresh_cam_fail_count);
        return;
    }

    my_zlog_info("refresh_cam success, windows:%d, enter count:%d",
                 refreshed_windows, s_refresh_cam_enter_count);
}

// 检查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;
}