package main

import (
	"encoding/json"
	"fmt"
	"os"

	"gitea.ceperka.net/rosti/lobby2/api"
	"gitea.ceperka.net/rosti/lobby2/nodes"
	"gitea.ceperka.net/rosti/lobby2/refresher"
	"github.com/urfave/cli/v2"
)

func masterAction(c *cli.Context) error {
	cfg := GetConfig()

	np := nodes.NewNodesProcessor(cfg.DumpPath, cfg.DropAfterSeconds)

	go np.DumpLoop()
	go np.GarbageCollection()

	api := api.NewAPI(np, cfg.APIListen, cfg.APIToken)
	api.Run()

	return nil
}

func nodeAction(c *cli.Context) error {
	cfg := GetConfig()

	r := refresher.NewRefresher(cfg.NodePath, cfg.ConfigPath)
	r.Loop()

	return nil
}

func printAction(c *cli.Context) error {
	cfg := GetConfig()

	np := nodes.NewNodesProcessor(cfg.DumpPath, cfg.DropAfterSeconds)

	nodes := np.List()
	for _, node := range nodes {
		body, err := json.MarshalIndent(node, "", "  ")
		if err != nil {
			fmt.Printf("failed to marshal node: %v\n", err)
			os.Exit(1)
		}

		fmt.Println(string(body))
	}

	return nil
}

func prometheusAction(c *cli.Context) error {
	cfg := GetConfig()

	np := nodes.NewNodesProcessor(cfg.DumpPath, cfg.DropAfterSeconds)

	pds := nodes.GetPrometheusSD(np, "node")

	for _, pd := range pds {
		body, err := json.MarshalIndent(pd, "", "  ")
		if err != nil {
			fmt.Printf("failed to marshal prometheus discovery: %v\n", err)
			os.Exit(1)
		}

		fmt.Println(string(body))
	}

	return nil
}