package alarm

import (
	"bytes"
	"git.quantgroup.cn/DevOps/enoch/service/data"
	"git.quantgroup.cn/DevOps/enoch/service/log"
	"github.com/influxdata/influxdb/client/v2"
)

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

	res, err := con.Query(q)
	if nil != err {
		logger.Error.Println("influxdb client init error", err)
	}
	if nil != res.Error() {
		logger.Error.Println("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
}
