package utils

import (
	"context"
	"errors"
	"time"

	"github.com/chromedp/chromedp"
)

type Allocator struct {
	context.Context

	ActTimeout time.Duration
}

func NewHeadlessAllocator(
	ctx context.Context,
) (Allocator, context.CancelFunc) {
	ctx, cancel := chromedp.NewExecAllocator(ctx,
		append(chromedp.DefaultExecAllocatorOptions[:],
			chromedp.Headless,
			chromedp.DisableGPU,
			chromedp.NoSandbox,
		)...,
	)

	mainCtx, mainCancel := chromedp.NewContext(ctx)

	cancelFunc := func() {
		mainCancel()
		cancel()
	}

	return Allocator{
		Context:    mainCtx,
		ActTimeout: 40 * time.Second,
	}, cancelFunc
}

func NewAllocator(
	ctx context.Context,
) (Allocator, context.CancelFunc) {
	ctx, cancel := chromedp.NewExecAllocator(ctx,
		append(chromedp.DefaultExecAllocatorOptions[:],
			// 去掉 chromedp.Headless
			chromedp.Flag("headless", false),
			chromedp.Flag("disable-gpu", false), // 可选，看系统需求
			chromedp.NoSandbox,
		)...,
	)

	mainCtx, mainCancel := chromedp.NewContext(ctx)

	cancelFunc := func() {
		mainCancel()
		cancel()
	}

	return Allocator{
		Context:    mainCtx,
		ActTimeout: 40 * time.Second,
	}, cancelFunc
}

func (c Allocator) IsXpathExist(xpath string) (bool, error) {
	ctx, cancel := context.WithTimeout(c.Context, c.ActTimeout)
	defer cancel()
	err := chromedp.Run(ctx,
		chromedp.WaitVisible(xpath, chromedp.BySearch),
	)
	if err != nil {
		if errors.Is(err, context.DeadlineExceeded) {
			return false, nil
		}
		return false, err
	}
	return true, nil
}
