// Package example contails some runners examples
package example

import (
	"encoding/json"
	"log/slog"
	"time"

	mqtt "github.com/eclipse/paho.mqtt.golang"

	"quantex.com/qfixdpl/src/app"
	"quantex.com/qfixdpl/src/client/api/async"
	googlechat "quantex.com/qfixdpl/src/client/notify/google"
	"quantex.com/qfixdpl/src/cmd"
	"quantex.com/qfixdpl/src/domain"
)

func AsyncRunner(cfg app.Config) error {
	slog.Info("Hello TryAsync")

	notify := googlechat.New(cfg.Notify.Google)

	asyncManager := async.New(cfg.Async, notify)

	asyncManager.Start()

	a := NewAux(asyncManager)
	a.run()

	cmd.WaitForInterruptSignal(nil)

	return nil
}

type Aux struct {
	async domain.Asyncer
}

func NewAux(a domain.Asyncer) *Aux {
	return &Aux{
		async: a,
	}
}

type msgAux struct {
	Message string
	Count   int64
	Time    time.Time
}

func (a *Aux) run() {
	const luckyNumber = 13

	msg := msgAux{
		Message: "Hello",
		Count:   luckyNumber,
		Time:    time.Now(),
	}

	const topic = "qfixdpl/try-async"

	a.async.Subscribe(topic, a.handler)

	a.async.Publish(topic, msg)
}

func (*Aux) handler(topic string, msg []byte) {
	var val msgAux

	err := json.Unmarshal(msg, &val)
	if err != nil {
		slog.Error(err.Error())
	}

	slog.Info(">>> Topic: %s, Msg: %+v", topic, val)
}

//lint:ignore U1000 client will be implemented if necessary
func (a *Aux) onConnectHandler(_ mqtt.Client) {
	const topic = "qfixdpl/try-async"

	a.async.Subscribe(topic, a.handler)
}
