package amqp

import (
	"crypto/tls"
	"log"

	"github.com/rabbitmq/amqp091-go"
	"gopkg.in/ini.v1"
)

func Config() (*ini.File, error) {
	return ini.Load("/etc/deevirt/config.ini")
}

func Publisher(body []byte) {
	config, _ := Config()

	amqp_config := amqp091.Config{
		Properties:      amqp091.NewConnectionProperties(),
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	amqp_config.Properties.SetClientConnectionName("producer-with-confirms")

	conn, err := amqp091.DialConfig(config.Section("broker").Key("uri").String(), amqp_config)
	if err != nil {
		log.Fatalf("producer: error in dial: %s", err)
	}
	defer conn.Close()

	log.Println("producer: got Connection, getting Channel")
	channel, err := conn.Channel()
	if err != nil {
		log.Fatalf("error getting a channel: %s", err)
	}
	defer channel.Close()

	//log.Printf("producer: publishing %dB body (%q)", len(*body), *body)
	_, err = channel.PublishWithDeferredConfirm(
		"vmcenter",
		"cluster.f242b4bb-b6d0-415f-b3f9-9e9d439532b5.dom.add",
		true,
		false,
		amqp091.Publishing{
			ContentType:  "text/plain",
			DeliveryMode: amqp091.Persistent,
			Body:         body,
		},
	)
	if err != nil {
		log.Fatalf("producer: error in publish: %s", err)
	}
}