package main

import (
	"context"
	"io"
	"log"
	"os"

	"github.com/fgm/izidic"

	"code.osinet.fr/fgm/sqs_demo/back/services"
)

func main() {
	os.Exit(int(main2(os.Stdout, os.Args[0], os.Args[1:])))
}

func main2(w io.Writer, name string, args []string) (exitCode byte) {
	ctx := context.Background()
	dic := Resolve(w, name, args)
	lister := dic.MustService(services.SvcLister).(func(ctx context.Context) string)
	qURL := lister(ctx)

	if false {
		receiver := dic.MustService(services.SvcReceiver).(func(ctx context.Context, qURL string))
		receiver(ctx, qURL)
	}
	consumer := dic.MustService(services.SvcConsumer).(func(ctx context.Context, qURL string) error)
	err := consumer(ctx, qURL)
	if err != nil {
		log.Printf("error in consumer: %v, aborting", err)
		exitCode = 1
	}

	log.Printf("exiting cleanly")
	return 0
}

func Resolve(w io.Writer, name string, args []string) *izidic.Container {
	dic := izidic.New()
	dic.Store(services.PName, name)
	dic.Store(services.PArgs, args)
	dic.Store(services.PWriter, w)
	dic.Store("handler", services.Handler(HandleDummy))

	dic.Register(services.SvcClient, services.SQSClientService)
	dic.Register(services.SvcConsumer, services.ConsumerService)
	dic.Register(services.SvcFlags, services.FlagsService)
	dic.Register(services.SvcLister, services.ListerService)
	dic.Register(services.SvcLogger, services.LoggerService)
	dic.Register(services.SvcReceiver, services.ReceiverService)

	dic.MustService(services.SvcFlags) // Store generated params before freeze.
	dic.Freeze()
	return dic
}
