package fastgpt

import (
	"github.com/go-resty/resty/v2"
	"log"
	"os"
)

// NewResty new resty client
func NewResty() *resty.Client {
	client := resty.New()
	logger := newLogger()
	client.SetRetryCount(2).
		SetLogger(logger).
		SetHeader("Content-Type", "application/json").
		SetBaseURL("https://fastgpt.gkscrm.com/api").
		SetHeader("Authorization", "Bearer "+getToken())

	return client
}

func NewDiyResty(token string) *resty.Client {
	client := resty.New()
	logger := newLogger()
	client.SetRetryCount(2).
		SetLogger(logger).
		SetHeader("Content-Type", "application/json").
		SetBaseURL(GetBaseUrl()).
		SetHeader("Authorization", "Bearer "+token)

	return client
}

// getToken 获取配置的可用的Token
func getToken() string {
	return "fastgpt-czbAiqKKse65hwwviZhwkgvyDEKE3aeB31Fx18oUsAGojyWQ672HdsWZi1E1C"
}

func GetBaseUrl() string {
	return "https://fastgpt.gkscrm.com/api"
}

type logger struct {
	l *log.Logger
}

func (l *logger) Errorf(format string, v ...interface{}) {
	l.output("ERROR RESTY "+format, v...)
}

func (l *logger) Warnf(format string, v ...interface{}) {
	l.output("WARN RESTY "+format, v...)
}

func (l *logger) Debugf(format string, v ...interface{}) {
	l.output("DEBUG RESTY "+format, v...)
}

func (l *logger) output(format string, v ...interface{}) {
	if len(v) == 0 {
		l.l.Print(format)
		return
	}
	l.l.Printf(format, v...)
}

// newLogger return a new logger
func newLogger() *logger {
	l := &logger{l: log.New(os.Stdout, "", log.Ldate|log.Lmicroseconds)}
	return l
}
