package request

import (
	// "bytes"
	"fmt"
	"net/http"
	"github.com/pquerna/ffjson/ffjson"
	"strings"
	"github.com/usual2970/util/random"
	"github.com/usual2970/util/time"
	"crypto/sha256"
	"encoding/base64"

)

type Client struct {
	appKey string
	appSecret string
	httpClient *http.Client
}

func (clt *Client) AppKey() string {
	return clt.appKey
}
func (clt *Client) AppSecret() string {
	return clt.appSecret
}

func NewClient(appKey,appSecret string, httpClient *http.Client) *Client {
	if httpClient == nil {
		httpClient = http.DefaultClient
	}
	return &Client{
		appKey:      appKey,
		appSecret:   appSecret,
		httpClient: httpClient,
	}
}

func (clt *Client) Post(url string,params interface{}) (resp interface{},err error){
	pBytes,err:=ffjson.Marshal(params)
	fmt.Println(string(pBytes))
	if err!=nil{
		return 
	}

	req,err:=http.NewRequest("POST",url,strings.NewReader(string(pBytes)))
	
	if err!=nil{
		return 
	}

	ctime:=time.NowCm()
	nonce:=string(random.RandomCreateBytes(64))

	pwDigest:=clt.PwDigest(ctime,nonce)

	
	req.Header.Add("Authorization","WSSE realm=\"SDP\", profile=\"UsernameToken\", type=\"AppKey\"")
	req.Header.Add("X-WSSE",
		fmt.Sprintf(`UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"`,
			clt.AppKey(),
			pwDigest,
			nonce,
			ctime,
		))
	req.Header.Add("Content-Type","application/json; charset=UTF-8")

	

	response,err:=clt.httpClient.Do(req)
	if err!=nil{
		fmt.Println(err)
		return 
	}
	defer response.Body.Close()
	fmt.Println(req.Header)
	return 
}


func (clt *Client) PwDigest(cmNow,nonce string) string{
	hash:=sha256.New()
	hash.Write([]byte(nonce+cmNow+clt.AppSecret()))
	md:=hash.Sum(nil)
	return base64.StdEncoding.EncodeToString(md)
	
}



