package collector

import (
	"encoding/json"
	"os/exec"
)

type Gateway struct {
	Name       string `json:"name"`
	Address    string `json:"address"`
	Status     string `json:"status"`
	Loss       string `json:"loss,omitempty"`
	Delay      string `json:"delay,omitempty"`
	Stddev     string `json:"stddev,omitempty"`
	Monitor    string `json:"monitor,omitempty"`
}

// CollectGateways liest OPNsense Gateways via configctl
func CollectGateways() []Gateway {
	out, err := exec.Command("/usr/local/sbin/configctl", "interface", "gateways", "status").Output()
	if err != nil {
		return nil
	}

	var raw []struct {
		Name             string `json:"name"`
		Address          string `json:"address"`
		Status           string `json:"status"`
		Loss             string `json:"loss"`
		Delay            string `json:"delay"`
		Stddev           string `json:"stddev"`
		Monitor          string `json:"monitor"`
		StatusTranslated string `json:"status_translated"`
	}

	if err := json.Unmarshal(out, &raw); err != nil {
		return nil
	}

	var gateways []Gateway
	for _, r := range raw {
		gw := Gateway{
			Name:    r.Name,
			Address: r.Address,
			Status:  r.StatusTranslated,
			Loss:    r.Loss,
			Delay:   r.Delay,
			Stddev:  r.Stddev,
			Monitor: r.Monitor,
		}
		// Normalisiere "~" zu leer
		if gw.Loss == "~" {
			gw.Loss = ""
		}
		if gw.Delay == "~" {
			gw.Delay = ""
		}
		if gw.Stddev == "~" {
			gw.Stddev = ""
		}
		if gw.Monitor == "~" {
			gw.Monitor = ""
		}
		gateways = append(gateways, gw)
	}

	return gateways
}
