package data

import (
	"bytes"
	"git.quantgroup.cn/DevOps/enoch/service/conf"
	"github.com/influxdata/influxdb/client/v2"
	"github.com/vrg0/go-common/logger"
)

func NewClient() client.Client {
	var httpConfig = client.HTTPConfig{
		Addr: conf.GlobalConfig.InfluxDb.Host + ":" + conf.GlobalConfig.InfluxDb.Port,
	}
	con, err := client.NewHTTPClient(httpConfig)

	if err != nil {
		logger.Error(err.Error())
	}

	return con
}

func Query(sql string, db string) []client.Result {
	con := NewClient()
	q := client.Query{Command: sql, Database: db}

	res, err := con.Query(q)
	if nil != err {
		logger.Error("influxdb client init error", err)
	}
	if nil != res.Error() {
		logger.Error("query error", db, sql, res.Error())
	}
	return res.Results
}

func QueryMonitor(sql string) []client.Result {
	return Query(sql, MONITOR)
}

func QuerySysName() []string {
	res := QueryMonitor(SYSNAME_SQL)
	var values = res[0].Series[0].Values
	sysName := make([]string, 0)
	for _, v := range values {
		sysName = append(sysName, v[1].(string))
	}
	return sysName
}

func QueryHost(sysName []string) map[string][]string {
	var sqlBuff bytes.Buffer

	for _, name := range sysName {
		sqlBuff.WriteString(HOST_SQL)
		sqlBuff.WriteString("'")
		sqlBuff.WriteString(name)
		sqlBuff.WriteString("';")
	}

	res := QueryMonitor(sqlBuff.String())

	nodeTree := make(map[string][]string)
	for index, result := range res {
		ipList := make([]string, 0)
		values := result.Series[0].Values
		for _, v := range values {
			ipList = append(ipList, v[1].(string))
		}
		nodeTree[sysName[index]] = ipList
	}
	return nodeTree
}
