package etcd

import (
	"context"
	"encoding/json"
	"log"
	"strings"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
)

type Node struct {
	IpManagement string `json:"ip_mgmt"`
}

func New(uri string) (*clientv3.Client, error) {
	etcd, err := clientv3.New(clientv3.Config{
		Endpoints:   strings.Split(uri, ","),
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Fatalf("Error connexion to etcd: %v", err)
	}

	return etcd, nil
}

func GetNodes(c *clientv3.Client, cluster_id string) map[string]Node {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	resp, _ := c.Get(ctx, "/cluster/"+cluster_id)

	var nodes map[string]Node

	err := json.Unmarshal(resp.Kvs[0].Value, &nodes)
	if err != nil {
		log.Fatal("Erreur lors du parsing du JSON: ", err)
	}

	return nodes
}
