package server

import (
	"context"
	"os"
	"os/signal"
	"rpirelay/config"
	"rpirelay/internal/api"
	"sync"
	"syscall"

	"github.com/spf13/cobra"
)

var cfgPaths []string

func NewCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use: "server",
		Run: startServer,
	}

	cmd.Flags().StringSliceVarP(&cfgPaths, "config", "c", []string{}, "config file paths")

	return cmd
}

func startServer(cmd *cobra.Command, args []string) {
	cfg, err := config.Load(cfgPaths...)
	if err != nil {
		panic(err)
	}

	lock := make(chan os.Signal, 1)
	signal.Notify(lock, syscall.SIGTERM, syscall.SIGINT)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	svcCtx, svcCancel := context.WithCancel(ctx)

	wg := &sync.WaitGroup{}

	wg.Add(1)

	// get system signal
	go func() {
		<-lock
		svcCancel()
	}()

	go func() {
		err := <-api.Start(svcCtx, cfg)
		if err != nil {
			panic(err)
		}
		wg.Done()
	}()

	// wait all service shutdown
	wg.Wait()
}
