package main

import (
	"errors"
	"flag"
	"fmt"
	"net/http"
	"rbd_exporter/connection"
	"rbd_exporter/logger"
	"rbd_exporter/metrics"
	"rbd_exporter/mytypes"
	"time"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)



// Here I initialize logger
func loggerInit() *zap.SugaredLogger {
	config := zap.NewDevelopmentConfig()
	config.EncoderConfig.TimeKey = "timestamp"
	config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	logger, err := config.Build()
	if err != nil {
		panic(fmt.Sprintf("Logger set up failed: %v", err))
	}
	
	return logger.Sugar()
}

func globalInit() (mainlogger *zap.SugaredLogger,params mytypes.Params){
	configFile := flag.String("config", "/etc/ceph/ceph.conf", "placement of ceph config file")
	_keyring := flag.String("keyring", "/etc/ceph/ceph.client.admin.keyring", "placement of ceph keyring file")
	flag.Parse()

	params.Config = *configFile
	params.Keyring = *_keyring

	mainlogger = loggerInit()
	logger.SetLogger(mainlogger)
	mainlogger.Info("Setting up logger is complete successfully")
	mainlogger.Info("Registering prom metrics")

	return mainlogger,params
}


func main() {
	mainlogger,params := globalInit()
	
	defer func() {
		err := logger.Logger.Sync()
		if err != nil {
			logger.Logger.Error("couldn't sync logger")
		}
	}()
	cephConn, err := connection.Connect(params)
	if err != nil {
		logger.Logger.Error(err)
		if wrapped := errors.Unwrap(err); wrapped != nil {
			logger.Logger.Error(wrapped)
		}
		panic(err)
	}
	defer cephConn.Conn.Shutdown()
	mainlogger.Info("Successfully connected to a cluster")

	http.Handle("/metrics", promhttp.Handler())


	server := http.Server{
		Addr: ":9040",
		ReadTimeout: 10 * time.Second,
		Handler: http.DefaultServeMux,
	}

	// HTTP runs in separate thread cuz it blocks further execution of main
	go func() {
		mainlogger.Info("Starting http server")
		// Here I check for errors if HTTP fails
		if err := server.ListenAndServe(); err != nil {
			mainlogger.Fatalf("HTTP server failed to start %v", err)
		}
		mainlogger.Info("HTTP server started")
	}()

	// if err := server.Shutdown(); err != nil {
	// 	logger.Logger.Errorf("https server shutdown failed",err)
	// }

	
	go metrics.GetMetrics(cephConn)

	select {}
}
