package main

import (
	"encoding/json"
	"escalation/prom/fetch"
	. "escalation/prom/model"
	"escalation/prom/write"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"time"

	"github.com/spf13/viper"
)

func GetAllNeededMetrics() []string {
	return []string{`tidb_executor_statement_total`, `tikv_engine_size_bytes`, `tiflash_system_current_metric_StoreSizeCapacity`, `tiflash_system_current_metric_StoreSizeUsed`}
}

// init the yaml file.
func setUpConfig() {
	viper.SetConfigName("conf")     // name of config file (without extension)
	viper.SetConfigType("yaml")     // REQUIRED if the config file does not have the extension in the name
	viper.AddConfigPath("./config") // optionally look for config in the working directory
	err := viper.ReadInConfig()     // Find and read the config file
	if err != nil {                 // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error config file: %w \n", err))
	}
}

// init the log.
func initLog(file_name string) {
	file := "./log/" + file_name
	logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
	if err != nil {
		panic(err)
	}
	log.SetOutput(logFile)
	log.SetPrefix("[Prometheus Data Fetching]")
	log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
	return
}

func main() {
	setUpConfig()
	initLog("increase.log")

	log.Println("start fetching...")

	for true {
		startBytes, _ := ioutil.ReadFile("./persist/start_time.json")
		var start_time CompletedTime
		err := json.Unmarshal(startBytes, &start_time)
		if err != nil {
			log.Println("error during deserialize start time: ", err)
		} else {
			log.Println("start time is: ", time.Unix(start_time.Timestamp, 0).Format("2006-01-02 15:04:05"))
		}
		// 15 mins.
		start_string := time.Unix(start_time.Timestamp, 0).UTC().Format("2006-01-02 15:04:05")
		end_string := time.Now().UTC().Format("2006-01-02 15:04:05")

		log.Println("start of fetching round time: ", start_string)
		log.Println("end of fetching round time:  ", end_string)

		token_auth0 := fetch.GetToken()
		log.Println("token for auth0 is: ", token_auth0)
		clusters := fetch.GetAllClusterInf(token_auth0)
		write.FetchAndWrite(GetAllNeededMetrics(), start_string, end_string, clusters)
		time.Sleep(3 * time.Minute)
	}

	// start_string := "2022-11-15 00:00:00"
	// end_string := "2022-11-17 07:59:59"

	// log.Println("start of fetching round time: ", start_string)
	// log.Println("end of fetching round time:  ", end_string)

	// token_auth0 := fetch.GetToken()
	// log.Println("token for auth0 is: ", token_auth0)
	// clusters := fetch.GetAllClusterInf(token_auth0)
	// write.FetchAndWrite(GetAllNeededMetrics(), start_string, end_string, clusters)

}
