package lxrod

import (
	"context"
	"git.listensoft.net/tool/jspkit/taxerr"

	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/devices"
	"github.com/go-rod/rod/lib/launcher"
)

// NewLauncher 创建一个新的 rod 浏览器启动器
func NewLauncher(ctx context.Context) *launcher.Launcher {
	return launcher.New().Context(ctx).Set("window-size", "1600,900").Headless(false)
}

// NewEdgeBrowser 创建一个由 rod chromium 模拟的 Edge 浏览器
func NewEdgeBrowser(ctx context.Context, u string) *rod.Browser {
	return rod.New().Context(ctx).DefaultDevice(EdgeLandscape).ControlURL(u)
}

// EdgeLandscape device.
var EdgeLandscape = devices.Device{
	Title:          "Edge Laptop with HiDPI screen",
	Capabilities:   []string{},
	UserAgent:      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
	AcceptLanguage: "en",
	Screen: devices.Screen{
		DevicePixelRatio: 2,
		Horizontal: devices.ScreenSize{
			Width:  1600,
			Height: 900,
		},
		Vertical: devices.ScreenSize{
			Width:  900,
			Height: 1600,
		},
	},
}.Landscape()

func (lxrod *Lxrod) NewUserMode(ctx context.Context) (b *rod.Browser, p *rod.Page, err error) {
	l := launcher.NewUserMode().Headless(false)
	l.Flags["disable-blink-features"] = []string{"AutomationControlled"}
	lxrod.Launcher = l
	wsURL, err := l.Launch()
	lxrod.WsURL = wsURL
	if err != nil {
		return nil, nil, taxerr.NewWebStuckTitle(true)
	}
	b = rod.New().NoDefaultDevice().ControlURL(wsURL).Context(ctx).MustConnect()
	p = b.MustPage().MustSetWindow(0, 0, 1600, 900).MustSetViewport(1600, 900, 1, false)
	lxrod.Browser = b
	return b, p, nil
}
