package apple

import (
	"context"
	"encoding/json"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/gclient"
	"github.com/gogf/gf/v2/net/gtrace"
	"github.com/gogf/gf/v2/os/glog"
	"sync"
)

type Client struct {
	Client *gclient.Client
}

var client *Client

func NewClient() *Client {
	sync.OnceFunc(func() {
		client = &Client{
			Client: g.Client(),
		}
	})()
	return client
}

func (c *Client) Redeem(ctx context.Context, req *RedeemReq) (resp *Resp[RedeemResp], err error) {
	ctx, span := gtrace.NewSpan(ctx, "AppleClient.Redeem")
	defer span.End()
	response, err := c.Client.ContentJson().Post(ctx, "http://kami-spider-monorepo:8000/api/apple/redeem", req)
	if err != nil {
		span.RecordError(err)
		return
	}
	resp = &Resp[RedeemResp]{}
	redeemResp := response.ReadAllString()
	glog.Info(ctx, "获取信息", redeemResp)
	err = json.Unmarshal([]byte(redeemResp), resp)
	return resp, err
}

func (c *Client) QueryBalance(ctx context.Context, req *QueryBalanceReq) (resp *Resp[QueryBalanceResp], err error) {
	ctx, span := gtrace.NewSpan(ctx, "AppleClient.QueryBalance")
	defer span.End()
	response, err := c.Client.ContentJson().Post(ctx, "http://kami-spider-monorepo:8000/api/apple/query-balance", req)
	if err != nil {
		span.RecordError(err)
		return
	}
	resp = &Resp[QueryBalanceResp]{}
	queryBalanceResp := response.ReadAllString()
	glog.Info(ctx, "获取信息", queryBalanceResp)
	err = json.Unmarshal([]byte(queryBalanceResp), resp)
	return resp, err
}

func (c *Client) Heartbeat(ctx context.Context, req *HeartBeatReq) (resp *Resp[HeartBeatResp], err error) {
	response, err := c.Client.ContentJson().Post(ctx, "http://kami-spider-monorepo:8000/api/apple/heartbeat", req)
	if err != nil {
		return
	}
	resp = &Resp[HeartBeatResp]{}
	heartbeatResp := response.ReadAllString()
	glog.Info(ctx, "获取信息", heartbeatResp)
	err = json.Unmarshal([]byte(heartbeatResp), resp)
	return resp, err
}
