package services

import (
	"context"
	"errors"
	"fmt"
	"go-account-register/libs"
	"log"
	"time"

	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/cdp"
)

type TwitterService struct{}

// 登录
func (*TwitterService) Login(id int) *libs.ErrorInfo {
	UserService := InitTwitterAccountService()
	user := UserService.GetInfo(int64(id))
	obj := Browser.GetBrowser(id, &libs.Fingerprint{
		Proxy: user.Proxy,
	})
	browser := obj.Browser
	page := obj.Page

	err3 := rod.Try(func() {
		// 创建 Cookie 对象
		cookies := user.Cookies
		log.Println("获取cookie", cookies)
		// 全局设置
		browser.SetCookies(cookies)
		page.MustNavigate("https://x.com/home").MustWaitLoad()
		page.MustWaitNavigation()
	})
	if e, ok := err3.(*cdp.Error); ok {
		if e.Code == -32000 && e.Message == "Inspected target navigated or closed" {
			Browser.CancelBrowser(id)
			return libs.ErrorCode["LoginFailed"]
		}
	}

	time.Sleep(3 * time.Second)
	url := page.MustEval("() => window.location.href").String()
	if url == "https://x.com/account/access" {
		Browser.CancelBrowser(id)
		return libs.ErrorCode["AccountLocked"]
	}
	log.Println(url)
	err1 := rod.Try(func() {
		page.Timeout(5 * time.Second).MustElement(`input[autocomplete="username"]`)
	})
	if err1 == nil {
		Browser.CancelBrowser(id)
		return libs.ErrorCode["LoginFailed"]
	}
	// 是否检测到侧边栏
	err2 := rod.Try(func() {
		page.Timeout(5 * time.Second).MustElement(`a[data-testid="AppTabBar_Profile_Link"]`)
	})

	if err2 != nil {
		Browser.CancelBrowser(id)
		return libs.ErrorCode["LoginFailed"]
	}

	// 是否检测到帖子列表
	err := rod.Try(func() {
		page.Timeout(5 * time.Second).MustElement(`article[data-testid="tweet"]`)
	})

	if errors.Is(err, context.DeadlineExceeded) {
		fmt.Println("请求空闲等待超时！")
		// 关闭浏览器
		Browser.CancelBrowser(id)
		return libs.ErrorCode["NetworkTimeout"]
	}
	if err != nil {
		fmt.Println(err)
	}

	return libs.ErrorCode["LoginSuccessful"]
}

// 退出登录
func (*TwitterService) Logout(id int) {
	Browser.CancelBrowser(id)
}
