package goroutines

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

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

func GoDisk(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 + "/disk"
		resp, err := http.Get(reqUrl)
		if err != nil {
			log.Println("Erreur de communication : " + reqUrl)
			continue
		}
		resp.Body.Close()

		var disks []disk.DiskFS
		if err := json.NewDecoder(resp.Body).Decode(&disks); err != nil {
			log.Println("Impossible de récupérer : " + reqUrl)
			continue
		}

		for _, disk := range disks {
			tags := map[string]string{ // tags (ex: host, env…)
				"host":       server,
				"device":     disk.Partition.Device,
				"mountpoint": disk.Partition.Mountpoint,
				"fstype":     disk.Usage.Fstype,
			}
			fields := map[string]interface{}{
				// Tous les champs TimesStat (numériques)
				"total":           disk.Usage.Total,
				"free":            disk.Usage.Free,
				"used":            disk.Usage.Used,
				"usedpcent":       disk.Usage.UsedPercent,
				"inodestotal":     disk.Usage.InodesTotal,
				"inodesused":      disk.Usage.InodesUsed,
				"inodesfree":      disk.Usage.InodesFree,
				"inodesusedpcent": disk.Usage.InodesUsedPercent,
			}

			// ---- point ----
			p := influxdb2.NewPoint(
				"disk",
				tags,
				fields,
				time.Now(),
			)

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

		log.Println("(", len(disks), ") Disks written to InfluxDB :"+reqUrl)
	}
}
