package main

import (
	"errors"
	"fmt"
	"net/http"
	"os"
	"time"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"go.uber.org/zap"
)

var params Params
var logger *zap.SugaredLogger

func getMetrics(cephConn CephConnector) {
	
	metrics := InitMetrics()
	prometheus.MustRegister(
		metrics.Total_rbd_requested_size_per_pool,
	)

	ticker := time.NewTicker(2 *  time.Second)
	defer ticker.Stop()

	for range ticker.C {
		var result []Pool = []Pool{}
		poolList, err := cephConn.ListPools()
		if err != nil {
			logger.Error("Cannot get list of pools")
			// do not exit but continue checking
			continue
		}

		for _, v := range poolList {
			x, _ := PoolFactory(cephConn, v)
			result = append(result, x)
		}

		metrics.Total_rbd_requested_size_per_pool.Reset()
		for _,v := range result {
			if !v.HasRBD {continue}
			FillMetrics(v,metrics)
		}
		fmt.Println("====================")
		// fmt.Println(result)
		
	}
}


func main() {
	cephConn, err := connect()
	if err != nil {
		fmt.Println(err)
		if wrapped := errors.Unwrap(err); wrapped != nil {
			fmt.Println(wrapped)
		}
		os.Exit(1)
	}
	defer cephConn.conn.Shutdown()
	logger.Info("Successfully connected")

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

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

	go getMetrics(cephConn)

	select {}

}
