package icsdblog

import (
	"bytes"
	"encoding/json"
	"fmt"
	"sync"

	"gitlab.com/cinnamon/voiceagent/icshttpclient"
)

// requiredParam
type RequiredLogParam struct {
	PrjCode        string `json:"prjCode"`
	Uuid           string `json:"uuid"`
	SourceIp       string `json:"sourceIp"`
	SourcePort     string `json:"sourcePort"`
	TrxId          string `json:"trxId"`
	TrxRequestDate string `json:"trxRequestDate"`
	TrxType        string `json:"trxType"`
	TargetIp       string `json:"targetIp"`
	TargetPort     string `json:"targetPort"`

	// NotRequiredParam
	ResultDate   string `json:"resultDate"`
	ResultStatus string `json:"resultStatus"`
	BranchCode   string `json:"branchCode"`
	PcIp         string `json:"pcIp"`
	CustomerCode string `json:"customerCode"`
	SinarioId    string `json:"sinarioId"`
	ReRecodeSeq  string `json:"reRecodeSeq"`
}

type DbInfo struct {
	Ip     string
	Port   string
	Url    string
	Method string

	m *sync.Mutex
}

var gDbInfo *DbInfo
var onceDbLog sync.Once

// DB 연동 정보 singleton으로 등록
func NewDbInfo(ip, port, url, method string) *DbInfo {
	onceDbLog.Do(func() {
		gDbInfo = &DbInfo{
			Ip:     ip,
			Port:   port,
			Url:    url,
			Method: method,
		}
	})

	return gDbInfo
}

// DB 정보 조회
func GetDbInfo() *DbInfo {
	return gDbInfo
}

// logInsert
// 우선 전부 string으로 처리되있어서 string으로 함....
func DbLogInsert(PrjCode, Uuid, SourceIp, SourcePort, TrxId, TrxRequestDate, TrxType, TargetIp, TargetPort string, args ...string) {

	// 가변인자도 한번에 같은 구조체에 넣어놨음 (TA, STT, TTS 다르지 않음)
	param := RequiredLogParam{PrjCode, Uuid, SourceIp, SourcePort, TrxId, TrxRequestDate, TrxType, TargetIp, TargetPort, args[0], args[1], args[2], args[3], args[4], args[5], args[6]}

	p, _ := json.Marshal(param)
	p1 := bytes.NewBuffer(p)

	logUrlInfo := GetDbInfo()
	c := icshttpclient.NewIcsHttpClient(logUrlInfo.Method, "http://"+logUrlInfo.Ip+":"+logUrlInfo.Port+"/"+logUrlInfo.Url, p1)
	c.Request.Header.Add("apiKey", "aaabbb-cccddd-1234567890")
	c.Request.Header.Add("Content-Type", "application/json")
	c.Request.ParseForm()

	resp, err := c.Do(c.Request)
	if err != nil {

		fmt.Println(err)
	} else {
		defer resp.Body.Close()
		fmt.Println(resp.StatusCode, resp)
		body := make([]byte, resp.ContentLength)
		resp.Body.Read(body)
		fmt.Println("==================\n", string(body))
	}
}
