package cg_sdk

import (
	"errors"
	"git.sxidc.com/go-tools/api_binding/http_binding/response"
	"git.sxidc.com/go-tools/utils/http_client"
	"time"
)

var timeoutDuration = TimeoutSec * time.Second
var baseUrl string
var httpClient *http_client.Client

const (
	TimeoutSec    = 30
	servicePrefix = "/cg/api/v1"
)

func Destroy() {
	if httpClient == nil {
		return
	}
	http_client.Destroy(httpClient)
	httpClient = nil
}

func Init(configBaseUrl string) error {
	baseUrl = configBaseUrl + servicePrefix

	if httpClient == nil {
		httpClient = http_client.New()
	}

	return nil
}

// 创建编码
func createEncode(req CreateEncodeJsonBody) (string, error) {
	postResponse, err := httpClient.NewRequest(http_client.WithNewRequestTimeout(timeoutDuration)).
		Post(baseUrl+"/encodeRule/encode/create", req)
	if err != nil {
		return "", err
	}

	resp := new(response.InfoResponse[string])
	err = postResponse.Json(resp)
	if err != nil {
		return "", err
	}

	if !resp.Success {
		return "", errors.New(resp.Msg)
	}

	return resp.Info, nil
}

// 查询编码配置
func getEncodeConfigInfo(tenantId string, namespace string, configName string) (*EncodeConfigInfo, error) {
	getResponse, err := httpClient.NewRequest(http_client.WithNewRequestTimeout(timeoutDuration)).
		Get(baseUrl+"/encodeConfig/get",
			http_client.WithRequestQueryParams(map[string]string{
				"tenantId":   tenantId,
				"namespace":  namespace,
				"configName": configName,
			}))
	if err != nil {
		return nil, err
	}

	resp := new(response.InfosResponse[EncodeConfigInfo])
	err = getResponse.Json(resp)
	if err != nil {
		return nil, err
	}

	if !resp.Success {
		return nil, errors.New(resp.Msg)
	}

	//TODO 到时候这里要修改下 编码配置
	if len(resp.Infos) != 1 {
		return nil, errors.New("编码配置查询错误")
	}

	return &resp.Infos[0], nil
}

func updateCodeStatusFree(req *UpdateEncodeJsonBody) error {
	putResponse, err := httpClient.NewRequest(http_client.WithNewRequestTimeout(timeoutDuration)).
		Put(baseUrl+"/encode/status/free", req)

	resp := new(response.IDResponse[string])
	err = putResponse.Json(resp)
	if err != nil {
		return err
	}

	if !resp.Success {
		return errors.New(resp.Msg)
	}

	return nil
}

// 修改编码状态为在使用中
func updateCodeStatusUse(req *UpdateEncodeJsonBody) error {
	putResponse, err := httpClient.NewRequest(http_client.WithNewRequestTimeout(timeoutDuration)).
		Put(baseUrl+"/encode/status/receive", req)

	resp := new(response.IDResponse[string])
	err = putResponse.Json(resp)
	if err != nil {
		return err
	}

	if !resp.Success {
		return errors.New(resp.Msg)
	}

	return nil
}