package main

import (
	_ "embed"
	"encoding/json"
	"github.com/rs/zerolog/log"
	checks "http-server-status/internal/pkg/checks"
	"net/http"
	"sync"
	"text/template"
)

//go:embed template/index.html
var s string

var (
	version                                = "development"
)

var checkList []checks.Check

func init()  {
	readConfig()
	log.Debug().Int("max_percent", c.Checks.HDD.MaxPercent).Msg("HDD CHECK")
	checkList = append(checkList, checks.HDD{c.Checks.HDD}, checks.Memory{Config: c.Checks.Memory}, checks.Load{Config: c.Checks.Load}, checks.Systemd{Config: c.Checks.Systemd})
}

func main() {

	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		res, gloableRes := checkSystem()
		if gloableRes == false {
			writer.WriteHeader(http.StatusInternalServerError)
		}

		t, err := template.New("todos").Parse(s)
		if err != nil {
			panic(err)
		}

		t.Execute(writer, map[string]interface{}{"checks":res, "version": version})

		//writer.Write([]byte(s))
	})
	http.HandleFunc("/data.json", handler)
	err := http.ListenAndServe(c.HTTP.Listen, nil)
	log.Fatal().Err(err).Msg("Shutdown")
}

func handler(w http.ResponseWriter, r *http.Request) {
	res, gloableRes := checkSystem()


	httpResposne := struct {
		Checks map[string]ResultReturn
		Config Config
	}{Checks: res, Config: c}

	resJson, err := json.Marshal(httpResposne)
	if err != nil {
		log.Fatal().Err(err).Interface("httpResponse", ResultReturn{}).Msg("Check Error")
	}
	if gloableRes {
		w.Write(resJson)
		return
	}
	http.Error(w, string(resJson), http.StatusInternalServerError)

}


type ResultReturn struct {
	Success bool `json:"success"`
	Data interface{} `json:"data"`
}

func checkSystem() (map[string]ResultReturn, bool) {
	globaleResult := true
	wg := sync.WaitGroup{}
	res := make(map[string]ResultReturn)
	for _, c := range checkList {
		wg.Add(1)
		go func(check checks.Check) {
			defer wg.Done()
			s, data, err := check.Execute()
			if err != nil {
				log.Error().Err(err).Msg("Cant execute check")
				return
			}
			log.Debug().Str("check", check.Name()).Bool("status", s).Interface("Data", data).Msg("Executed Check, got Results")
			if s == false {
				globaleResult = false
			}
			res[check.Name()] = ResultReturn{
				Success: s,
				Data: data,
			}
		}(c)
	}
	wg.Wait()

	return res, globaleResult
}