package events

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

	"deevirt.fr/compute/pkg/config"
	"deevirt.fr/compute/pkg/schema"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"libvirt.org/go/libvirt"

	pb "deevirt.fr/compute/pkg/api/proto"
)

type Qemu struct {
	NodeID       string
	CompanyID    string
	DatacenterID string
	DomainID     string
	Event        *libvirt.DomainQemuMonitorEvent
}

func QemuEvents(c *libvirt.Connect, d *libvirt.Domain, event *libvirt.DomainQemuMonitorEvent) {
	var desc schema.Domain
	config, _ := config.New()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	domainID, _ := d.GetUUIDString()
	xmlDesc, _ := d.GetXMLDesc(0)
	err := xml.Unmarshal([]byte(xmlDesc), &desc)
	if err != nil {
		log.Fatalln(err)
	}

	e, _ := json.Marshal(&Qemu{
		NodeID:       config.NodeID,
		CompanyID:    desc.Metadata.DeevirtInstance.DeevirtCompanyID,
		DatacenterID: desc.Metadata.DeevirtInstance.DeevirtDatacenterID,
		DomainID:     domainID,
		Event:        event,
	})

	conn, err := grpc.NewClient(strings.Join(config.Manager.Peers, ","), grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("Erreur de connexion : %v", err)
	}
	defer conn.Close()
	client := pb.NewDomainClient(conn)

	client.Event(ctx, &pb.DomainEventRequest{
		Event: e,
	})
}
