package domain

import (
	"context"

	"deevirt.fr/compute/pkg/api/proto"
	"libvirt.org/go/libvirt"
)

type Events struct {
	NodeID       string
	CompanyID    string
	DatacenterID string
	Config       []byte
	DomainID     string
	State        int
	Event        *libvirt.DomainQemuMonitorEvent
}

type EventsDetail map[string]string

func (d *Domain) Event(ctx context.Context, req *proto.DomainEventRequest) (*proto.DomainEventResponse, error) {
	/*var events Events

	err := json.Unmarshal(req.Event, &events)
	if err != nil {
		fmt.Println("Erreur lors du décodage JSON:", err)
	}

	var edetail EventsDetail

	if events.Event.Event == "MIGRATION" {
		err = json.Unmarshal([]byte(events.Event.Details), &edetail)
		if err != nil {
			fmt.Println("Erreur lors du décodage JSON:", err)
		}

		if edetail["status"] == "setup" {
			r, _ := d.Store.Get(fmt.Sprintf("/etc/libvirt/qemu/%s/%s", events.NodeID, events.DomainID))

			if r != nil {
				var j raft.DomainStore
				json.Unmarshal(r, &j)
				j.Migrate = true

				new, _ := json.Marshal(j)
				d.Store.Set(fmt.Sprintf("/etc/libvirt/qemu/%s/%s", events.NodeID, events.DomainID), new)
			} else {
				new, _ := json.Marshal(raft.DomainStore{
					Config:  string(events.Config),
					State:   events.State,
					Migrate: false,
				})
				d.Store.Set(fmt.Sprintf("/etc/libvirt/qemu/%s/%s", events.NodeID, events.DomainID), new)
			}

			fmt.Printf("%s => %v\n", events.NodeID, edetail)
		} else if edetail["status"] == "completed" {
			r, _ := d.Store.Get(fmt.Sprintf("/etc/libvirt/qemu/%s/%s", events.NodeID, events.DomainID))

			if r != nil {
				var j raft.DomainStore
				json.Unmarshal(r, &j)

				if j.Migrate {
					d.Store.Delete(fmt.Sprintf("/etc/libvirt/qemu/%s/%s", events.NodeID, events.DomainID))
				}
			}

			fmt.Printf("%s => %v\n", events.NodeID, edetail)
		}
	}

	// AMQP - On envoi l'évènement brut
	/*e, _ := json.Marshal(events.Event)
	a, _ := amqp.NewAMQP()
	a.Publisher("vmcenter",
		"events."+events.CompanyID+
			"."+events.DatacenterID+
			"."+events.DomainID,
		e)
	defer a.Close()*/

	return &proto.DomainEventResponse{}, nil
}
