package logger

import (
	"encoding/json"
	"game-driver/config"
	tencentcloud_cls_sdk_go "github.com/tencentcloud/tencentcloud-cls-sdk-go"
	"time"
)

type TenCls struct {
	p   *tencentcloud_cls_sdk_go.AsyncProducerClient
	key string
}

func (t *TenCls) Write(p []byte) (n int, err error) {
	s := make(map[string]string)
	_ = json.Unmarshal(p, &s)
	s["key"] = t.key
	delete(s, "ts")
	clsLog := tencentcloud_cls_sdk_go.NewCLSLog(time.Now().Unix(), s)
	err = t.p.SendLog(config.C.Log.TencentCLS.TopicID, clsLog, nil)
	return len(p), err
}

func (t *TenCls) Start() {
	t.p.Start()
}

func (t *TenCls) Close() error {
	return t.p.Close(60_000)
}

func NewTenCls(code string) (*TenCls, error) {
	producerConfig := tencentcloud_cls_sdk_go.GetDefaultAsyncProducerClientConfig()
	producerConfig.Endpoint = config.C.Log.TencentCLS.Endpoint
	producerConfig.AccessKeyID = config.C.Log.TencentCLS.SecretID
	producerConfig.AccessKeySecret = config.C.Log.TencentCLS.SecretKey

	producerInstance, err := tencentcloud_cls_sdk_go.NewAsyncProducerClient(producerConfig)
	if err != nil {
		return nil, err
	}

	t := &TenCls{
		p:   producerInstance,
		key: code,
	}
	return t, nil
}
