package main

import (
	"github.com/prometheus/client_golang/prometheus"
	"net/http"
	_ "net/http/pprof"
	"sparrow/pkg/rpcs"
	"sparrow/pkg/server"
)

var deviceOnlineCount prometheus.Gauge
var deviceMessageCount *prometheus.CounterVec

func main() {

	// init server
	err := server.Init(rpcs.MQTTAccessName)
	if err != nil {
		server.Log.Fatal(err)
		return
	}

	a, err := NewAccess()
	if err != nil {
		server.Log.Fatal(err)
		return
	}

	// register a rpc service
	err = server.RegisterRPCHandler(a)
	if err != nil {
		server.Log.Errorf("Register RPC service Error: %s", err)
		return
	}

	// register a tcp service for mqtt
	err = server.RegisterTCPHandler(a.MqttBroker)
	if err != nil {
		server.Log.Errorf("Register TCP service Error: %s", err)
		return
	}

	deviceOnlineMetric := &server.Metric{
		ID:          "device_online_count",
		Name:        "device_online_count",
		Description: "MQTT Device Online Count",
		Type:        "gauge",
	}

	server.RegisterMetric(deviceOnlineMetric)
	deviceOnlineCount = deviceOnlineMetric.MetricCollector.(prometheus.Gauge)

	go func() {
		pprofPort := "6060"
		server.Log.Infof("pprof server started at :%s/debug/pprof", pprofPort)
		if err := http.ListenAndServe(":"+pprofPort, nil); err != nil {
			server.Log.Errorf("pprof server failed: %v", err)
		}
	}()

	// start to run
	err = server.Run()
	if err != nil {
		server.Log.Fatal(err)
	}
}
