package main

import (
	routing "git.coopgo.io/coopgo-platform/routing-service"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	SolidarityServiceHandler "solidarity-service/handler"
	api "solidarity-service/interoperability/solidarity-api/server"
	grpcserver "solidarity-service/servers/grpc/server"
	"solidarity-service/storage"
)

func main() {
	zerolog.TimeFieldFormat = zerolog.TimeFormatUnix

	cfg, err := ReadConfig()
	if err != nil {
		panic(err)
	}

	var (
		serviceName         = cfg.GetString("name")
		grpcEnable          = cfg.GetBool("services.grpc.enable")
		solidarityApiEnable = cfg.GetBool("services.solidarity-api.enable")
		routingServiceType  = cfg.GetString("routing.type")
		valhallaBaseUrl     = cfg.GetString("routing.valhalla.base_url")
	)
	log.Info().Msg("Running " + serviceName)
	storageService, err := storage.NewStorage(cfg)
	if err != nil {
		log.Fatal().Err(err).Msg("Could not initiate the storage service")
		return
	}
	routing, err := routing.NewRoutingService(routingServiceType, valhallaBaseUrl)
	if err != nil {
		log.Fatal().Err(err).Msg("Could not initiate the routing service")
		return
	}
	handler, err := SolidarityServiceHandler.NewSolidarityServiceHandler(cfg, routing, storageService)
	if err != nil {
		log.Fatal().Err(err).Msg("Could not initiate the solidarity service handler")
		return
	}

	failed := make(chan error)
	if grpcEnable {
		log.Info().Msg("Running gRPC server")
		go grpcserver.Run(failed, cfg, handler)
	}

	if solidarityApiEnable {
		log.Info().Msg("Running Interoperability REST API")
		go api.Run(cfg, handler, storageService)
	}

	err = <-failed

	log.Fatal().Err(err).Msg("Terminating")
}
