package proxy

import (
	"bytes"
	"fmt"
	"io"
	"net/http"

	"github.com/sirupsen/logrus"
	"gopkg.in/elazarl/goproxy.v1"
)

type UserInfo struct {
	UID      string
	SecUID   string
	ShortID  string
	RealName string
	Nickname string
}

func WithUserInfo(duration int) Option {
	return func(p *Proxy) {
		p.proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
			if resp.StatusCode != 200 {
				return resp
			}

			if resp.Request.Host != "www.douyin.com" {
				return resp
			}

			if resp.Request.URL.Path != "/user/self" {
				return resp
			}

			body, err := io.ReadAll(resp.Body)
			if err != nil {
				logrus.Error(err)
				return resp
			}
			resp.Body.Close()

			// 添加定时刷新
			codes := `
<!------------------->
<script nonce>
var hookFans = function (){
	document.querySelector('div[data-e2e="user-info-fans"]').click()
	setTimeout( () => document.querySelector('div[data-e2e="user-fans-container"]').parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.querySelector('svg').parentElement.click(), 2*1000)
}
</script>

<script nonce>
if (location.href.startsWith("https://www.douyin.com/user/self")) {
	console.log(">>>>>>>>>>>>>>>>>>>>>>>>>> start hook fans")
	var interval = setInterval(hookFans, (%d+Math.random()*100 %% %d)*1000)
	// setTimeout(() => location.reload, 5*60*1000)
}
</script>
</head>
<!------------------->
`
			codes = fmt.Sprintf(codes, duration, duration)
			body = bytes.Replace(body, []byte("</head>"), []byte(codes), 1)
			resp.Body = io.NopCloser(bytes.NewReader(body))

			// remove Content-Security-Policy
			resp.Header.Del("Content-Security-Policy")

			go p.processUserInfo(body)

			return resp
		})
	}
}
