package yu_okx

import (
	"encoding/json"
	yu_const "gogs.qqck.cn/s/tools/const"
	yu_curl "gogs.qqck.cn/s/tools/curl"
	yu_fast "gogs.qqck.cn/s/tools/fast"
	yu_hex "gogs.qqck.cn/s/tools/hex"
	yu_json "gogs.qqck.cn/s/tools/json"
	yu_rand "gogs.qqck.cn/s/tools/rand"
	yu_strconv "gogs.qqck.cn/s/tools/strconv"
	"time"
)

type V5Priapi struct {
	host string
	curl *yu_curl.Request
}

func NewV5Priapi() (t *V5Priapi) {
	t = &V5Priapi{}

	j_bootid := make([]byte, 36)
	yu_rand.Rand.ReadEx(j_bootid, yu_const.HexLowerBytes)
	j_bootid[8], j_bootid[13], j_bootid[18], j_bootid[23] = '-', '-', '-', '-'
	j_bootid_s := yu_fast.B2S(j_bootid)

	t.host = "https://www.okx.ac"
	t.curl = yu_curl.NewRequest()
	t.curl.SetHeader("change", "1")
	t.curl.SetUserAgent("OKEx-guanwang/6.72.1 (V1916A; U; Android 9; zh-CN;) locale=zh-CN")
	t.curl.SetHeader("devid", j_bootid_s)
	t.curl.SetHeader("platform", "android")
	t.curl.SetHeader("real-app-version", "6.72.1")
	t.curl.SetHeader("x-utc", "+08:00")
	t.curl.SetHeader("fingerprint-id", j_bootid_s)
	t.curl.SetHeader("risk-params", "fingerprint-id="+j_bootid_s+"&session-id="+j_bootid_s+"_app_start_"+yu_strconv.FormatInt64(time.Now().UnixMilli()))
	t.curl.SetHeader("lua-version", "6.73.2")
	t.curl.SetHeader("app_web_mode", "pro")
	t.curl.SetHeader("x-id", yu_hex.Lower(yu_rand.Bytes(16))) // 3457f9e63a8ecee647b3b3a61fdddc1d
	return
}

func (t *V5Priapi) Close() {
	t.curl.Close()
}

// SetProxy 设置代理
//
//	@Description:
//	@param proxy 格式 ProxyType://user:pass@host:port，ProxyType: http, socks4, socks4a, socks5, socks5h，设置为""以取消代理
func (t *V5Priapi) SetProxy(proxy string) *V5Priapi {
	t.curl.SetProxy(proxy)
	return t
}

func (t *V5Priapi) request(method string, path string, post any, resp any) bool {
	switch method {
	case "GET":
		t.curl.Get(t.host + path)
	case "POST":
		j_json, j_err := json.Marshal(post)
		if j_err != nil {
			return false
		}
		t.curl.Post(t.host+path, j_json)
	}
	if t.curl.RespStatusCode() != 200 {
		return false
	}
	if resp == nil {
		return true
	}
	// Code string `json:"code"`
	// Msg  string `json:"msg"`
	// Data any    `json:"data"`
	// println(t.curl.RespBodyS())
	j_data := yu_json.GetBytes(t.curl.RespBody(), "data").String()
	if j_data == "" {
		return false
	}
	return json.Unmarshal(yu_fast.S2B(j_data), resp) == nil
}
