package tiktok

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi"
	"net/http"
	"strings"
)

func (a *API) GetAppID() string {
	return a.clientKey
}

func (a *API) GetSecret() string {
	return a.clientSecret
}

func New(clientSecret, clientKey string, config ...*platformapi.APIConfig) *API {
	curConfig := platformapi.DefAPIConfig
	if len(config) > 0 {
		curConfig = *config[0]
	}
	return &API{
		clientSecret: clientSecret,
		clientKey:    clientKey,
		client:       &http.Client{Timeout: curConfig.ClientTimeout},
		config:       &curConfig,
	}
}

func (a *API) AccessAPI2(url string, params map[string]interface{}) (retVal map[string]interface{}, err error) {
	data, err := json.Marshal(params)
	if err != nil {
		return nil, err
	}
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			request, _ := http.NewRequest(http.MethodPost, url, strings.NewReader(string(data)))
			request.Header.Set("Content-Type", "application/json")
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			retVal = jsonResult1
			return platformapi.ErrLevelSuccess, nil
		})
	return retVal, err
}
