package goroutines

import (
	"context"
	"encoding/json"
	"log"
	"net/http"
	"time"

	"github.com/evoliatis/buildup/memory"
	influxdb2 "github.com/influxdata/influxdb-client-go/v2"
)

func GoMem(server, INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN string, tick int) {

	// Connexion
	client := influxdb2.NewClient(INFLUXDB_URL, INFLUXDB_TOKEN)
	defer client.Close()

	writeAPI := client.WriteAPIBlocking(INFLUXDB_ORG, INFLUXDB_BUCKET)

	ticker := time.NewTicker(time.Duration(tick) * time.Second)
	defer ticker.Stop()

	for range ticker.C {
		// Récupération des valeurs
		reqUrl := "http://" + server + "/mem"
		resp, err := http.Get(reqUrl)
		if err != nil {
			log.Println("Erreur de communication : " + reqUrl)
			continue
		}
		resp.Body.Close()

		var mem memory.MemInfo
		if err := json.NewDecoder(resp.Body).Decode(&mem); err != nil {
			log.Println("Impossible de récupérer : " + reqUrl)
			continue
		}

		// ---- point ----
		tags := map[string]string{ // tags (ex: host, env…)
			"host": server,
		}
		fields := map[string]interface{}{
			// Tous les champs TimesStat (numériques)
			"total":           mem.Virtual.Total,
			"available":       mem.Virtual.Available,
			"used":            mem.Virtual.Used,
			"used_pcent":      mem.Virtual.UsedPercent,
			"free":            mem.Virtual.Free,
			"active":          mem.Virtual.Active,
			"inactive":        mem.Virtual.Inactive,
			"cached":          mem.Virtual.Cached,
			"dirty":           mem.Virtual.Dirty,
			"shared":          mem.Virtual.Shared,
			"swap_total":      mem.Swap.Total,
			"swap_used":       mem.Swap.Used,
			"swap_used_pcent": mem.Swap.UsedPercent,
			"swap_free":       mem.Swap.Free,
			"swap_pgin":       mem.Swap.PgIn,
			"swap_pgout":      mem.Swap.PgOut,
			"swap_pgfault":    mem.Swap.PgFault,
		}
		p := influxdb2.NewPoint(
			"memory",
			tags,
			fields,
			time.Now(),
		)

		// Ecriture
		if err := writeAPI.WritePoint(context.Background(), p); err != nil {
			log.Printf("write failed: %v\n", err)
		}

		log.Println("memory written to InfluxDB : ", reqUrl)
	}
}
