package service

import (
	"encoding/json"
	"fmt"
	"git.quantgroup.cn/DevOps/enoch/service/end_points"
	"github.com/influxdata/influxdb/client/v2"
	"time"
)

func AgentMsgProcess(msg string) {
	chunkMsg := enn_points.ChunkMsg{}
	err := json.Unmarshal([]byte(msg), &chunkMsg)
	if err != nil {
		fmt.Println(err)
	}

	buildMetricsInfluxMsg(chunkMsg)
}

func buildMetricsInfluxMsg(chunkMsg enn_points.ChunkMsg) {
	for _, p := range chunkMsg.EndPoints {
		tags := make(map[string]string, )
		tags["sys_name"] = chunkMsg.AppName
		tags["host"] = chunkMsg.Ip
		fields := make(map[string]interface{})
		var metrics = p.Metrics
		var health = p.Health

		var status = health.Status
		if "UP" == status.Code {
			fields["sever_status"] = 1
		}
		var diskSpace = health.Details.DiskSpace.Details

		fields["disk_tol"] = diskSpace.Total
		fields["disk_free"] = diskSpace.Free
		fields["disk_threshold"] = diskSpace.Threshold

		fields["mem_tol"] = metrics.Mem
		fields["mem_free"] = metrics.MemFree

		fields["heap_tol"] = metrics.Heap
		fields["heap_init"] = metrics.HeapInit
		fields["heap_used"] = metrics.HeapUsed

		fields["nonheap_tol"] = metrics.Nonheap
		fields["nonheap_init"] = metrics.NonheapInit
		fields["nonheap_used"] = metrics.NonheapUsed
		fields["nonheap_commit"] = metrics.NonheapCommitted

		fields["thread_tol"] = metrics.ThreadsTotalStarted
		fields["thread_peak"] = metrics.ThreadsPeak
		fields["thread_daemon"] = metrics.ThreadsDaemon

		fields["class_tol"] = metrics.Classes
		fields["class_loaded"] = metrics.ClassesLoaded
		fields["class_unloaded"] = metrics.ClassesUnloaded

		fields["gc_parnew_count"] = metrics.GcParnewCount
		fields["gc_parnew_time"] = metrics.GcParnewTime
		fields["gc_concurrent_mark_sweep"] = metrics.GcConcurrentmarksweepCount
		fields["gc_concurrent_mark_time"] = metrics.GcConcurrentmarksweepTime

		fields["processors"] = metrics.Processors

		unix := time.Unix(0, p.Timestamp)
		if (len(pointSlice) == batchSize) {
			go batchWrite(pointSlice)
			pointSlice = make([]*client.Point, 0, batchSize)
		}
		point, _ := client.NewPoint("machine_info", tags, fields, unix)
		pointSlice = append(pointSlice, point)
	}

}
