package cn.sikey.selenium.util;

import cn.hutool.http.HttpStatus;
import cn.sikey.framework.common.exception.ServiceException;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;


/**
 * @Author: nelson
 * @Date: 2025/6/28
 * @Description: 会话
 */
public class WebDriverContextManagerUtil {

    public final static Cache<String, DriverSession> sessionMap = CacheBuilder.newBuilder()
            .maximumSize(10000L)
            .expireAfterWrite(30, TimeUnit.MINUTES)
            .build();


    private static final long DEFAULT_TIMEOUT = 30;

    // 创建新的 WebDriver 会话
    public static String createSession(String url) throws MalformedURLException {
        return createSession(url, DEFAULT_TIMEOUT);
    }

    public static String createSession(String url, long timeoutSeconds) throws MalformedURLException {
        String sessionId = generateSessionId();

        WebDriver driver = getDriverConfig(url);

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeoutSeconds));

        sessionMap.put(sessionId, new DriverSession(driver, wait));
        return sessionId;
    }

    // 获取现有会话
    public static DriverSession getSession(String sessionId) {
        DriverSession session = sessionMap.getIfPresent(sessionId);
        if (session == null) {
            throw new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, "无效的会话ID");
        }
        return session;
    }

    public static WebDriver getDriver(String sessionId) {
        return getSession(sessionId).getDriver();
    }

    public static WebDriverWait getWait(String sessionId) {
        return getSession(sessionId).getWait();
    }

    // 销毁会话
    public static void destroySession(String sessionId) {
        DriverSession session = sessionMap.getIfPresent(sessionId);
        if (session != null) {
            session.getDriver().quit();
        }
    }

    // 生成唯一会话ID
    private static String generateSessionId() {
        return "SID_" + System.currentTimeMillis() + "_" + (int) (Math.random() * 1000);
    }

    // 会话数据封装类
    public static class DriverSession {
        private final WebDriver driver;
        private final WebDriverWait wait;
        private final LocalDateTime createTime = LocalDateTime.now();

        public DriverSession(WebDriver driver, WebDriverWait wait) {
            this.driver = driver;
            this.wait = wait;
        }

        public WebDriver getDriver() {
            return driver;
        }

        public WebDriverWait getWait() {
            return wait;
        }

        public LocalDateTime getCreateTime() {
            return createTime;
        }
    }

    public static WebDriver getDriverConfig(String url) throws MalformedURLException {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        options.addArguments("--headless=new");

        // 设置 W3C 标准能力
        options.setCapability("se:vncEnabled", true);
        options.setCapability("se:recordVideo", false);

        WebDriver driver = new RemoteWebDriver(
                new URL(url),
                options
        );
        return driver;
    }

}
