package com.spider.quartz.util;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Playwright;

import java.util.Arrays;
import java.util.List;

public class BrowserSingleton {
    // 私有静态实例
    private static Browser instance;
    private static Playwright playwright;

    // 私有构造函数，禁止外部实例化
    private BrowserSingleton() {}

    // 全局访问点
    public static synchronized Browser getInstance() {
        if (instance == null) {
            // 初始化 Playwright 和 Browser
            playwright = Playwright.create();
            // 浏览器启动配置（适配1.40+版本）
            List<String> browserArgs = Arrays.asList(
                    "--disable-gpu",
                    "--disable-extensions",
                    "--no-sandbox",
                    "--disable-dev-shm-usage",
                    "--lang=zh-CN" // 模拟中文浏览器，避免页面语言切换
            );
            BrowserType.LaunchOptions launchOptions = new BrowserType.LaunchOptions()
                    .setHeadless(true)
                    .setArgs(browserArgs)
                    .setTimeout(120000); // 浏览器启动超时
            instance = playwright.chromium().launch(launchOptions);
        }
        return instance;
    }

    // 关闭资源
    public static synchronized void close() {
        if (instance != null) {
            instance.close();
            instance = null;
        }
        if (playwright != null) {
            playwright.close();
            playwright = null;
        }
    }
}

