package goroutines

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

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

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

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

		for _, net := range nets {

			tags := map[string]string{ // tags (ex: host, env…)
				"host":         "linux",
				"name":         net.Interface.Name,
				"mtu":          strconv.FormatInt(int64(net.Interface.MTU), 10),
				"hardwareaddr": net.Interface.HardwareAddr,
			}
			fields := map[string]interface{}{ // Données à stocker
				"bytesent":   net.IO.BytesSent,
				"byterecv":   net.IO.BytesRecv,
				"packetsent": net.IO.PacketsSent,
				"packetrecv": net.IO.PacketsRecv,
				"errorin":    net.IO.Errin,
				"errorout":   net.IO.Errout,
				"dropin":     net.IO.Dropin,
				"dropout":    net.IO.Dropout,
				"fifoin":     net.IO.Fifoin,
				"fifoout":    net.IO.Fifoout,
			}
			// ---- points ----
			p := influxdb2.NewPoint(
				"network",
				tags,
				fields,
				time.Now(),
			)

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

		log.Println("(", len(nets), ") network written to InfluxDB : "+reqUrl)
	}
}
