package bot

import (
	"fmt"
	"log"
	"os"

  "vigil/pkg/config"

	"gosrc.io/xmpp"
	"gosrc.io/xmpp/stanza"
)

func Run(c config.Config) error {
	xc := xmpp.Config{
		TransportConfiguration: xmpp.TransportConfiguration{
      Address: c.XMPP.Address,
		},
		Jid:          c.XMPP.Jid,
		Credential:   xmpp.Password(c.XMPP.Credential),
		StreamLogger: os.Stdout,
		Insecure:     c.XMPP.Insecure,
	}

	router := xmpp.NewRouter()
	router.HandleFunc("message", handleMessage)

	client, err := xmpp.NewClient(&xc, router, errorHandler)
	if err != nil {
		log.Fatalf("%+v", err)
    return err
	}

	// If you pass the client to a connection manager, it will handle the reconnect policy
	// for you automatically.
	cm := xmpp.NewStreamManager(client, nil)
	log.Fatal(cm.Run())
  return nil
}

func handleMessage(s xmpp.Sender, p stanza.Packet) {
	msg, ok := p.(stanza.Message)
	if !ok {
		_, _ = fmt.Fprintf(os.Stdout, "Ignoring packet: %T\n", p)
		return
	}

	_, _ = fmt.Fprintf(os.Stdout, "Body = %s - from = %s\n", msg.Body, msg.From)
	reply := stanza.Message{Attrs: stanza.Attrs{To: msg.From}, Body: msg.Body}
	_ = s.Send(reply)
}

func errorHandler(err error) {
	fmt.Println(err.Error())
}