package app

import (
	"flag"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"git.espin.casa/albert/cml04-mediciones/internal/client"
	"git.espin.casa/albert/cml04-mediciones/internal/routes"
	"git.espin.casa/albert/logger"
	"github.com/julienschmidt/httprouter"
)

func Run() error {
	// setup flags
	httpAddr := flag.String("bind-addr", "0.0.0.0:9100", "HTTP server address")
	apiAddr := flag.String("api-addr", "mediciones-service", "REST API server address")
	apiPort := flag.Int("api-port", 3000, "REST API server port")
	//apiAddr := flag.String("api-addr", "10.1.152.13", "REST API server address")
	//apiPort := flag.Int("api-port", 9210, "REST API server port")
	logLevel := flag.String("level", "debug", "Log level")
	flag.Parse()
	// setup logger
	log := logger.New(os.Stdout, *logLevel)
	// create router
	router := httprouter.New()
	// create api client
	client := client.NewClient(&client.ClientConfig{
		Host: *apiAddr,
		Port: *apiPort,
		Base: "api/v1",
	})
	// create routes
	routes.CreateRoutes(router, client)
	// serve static files
	router.ServeFiles("/assets/*filepath", http.Dir("assets"))
	// start the http server
	go func() {
		http.ListenAndServe(*httpAddr, router)
	}()
	// info banner
	log.Info("started cml04-mediciones service", logger.LogFields{
		"http_bind_address": *httpAddr,
		"api_address":       *apiAddr,
		"api_port":          *apiPort,
		"log_level":         *logLevel,
	})
	// wait signal to finish
	signal := WaitSignal()
	log.Info("signal received", logger.LogFields{
		"signal": signal,
	})
	return nil
}

// WaitSignal catching exit signal
func WaitSignal() os.Signal {
	ch := make(chan os.Signal, 2)
	signal.Notify(
		ch,
		syscall.SIGINT,
		syscall.SIGQUIT,
		syscall.SIGTERM,
	)
	for {
		sig := <-ch
		switch sig {
		case syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM:
			return sig
		}
	}
}
