package main

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

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

var (
	version                                = "development"
)

var checkList []checks.Check

func init()  {
	readConfig()
	pp := log.Output(zerolog.ConsoleWriter{Out: os.Stdout})
	multi := zerolog.MultiLevelWriter(pp)
	log.Logger = zerolog.New(multi).With().Timestamp().Caller().Logger()
	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}, checks.Version{Config: c.Checks.Version})
}

func auth(fn http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if c.Auth.Enabled {
			user, pass, _ := r.BasicAuth()
			if !check(user, pass) {
				w.Header().Set("WWW-Authenticate", `Basic realm="MY REALM"`)
				http.Error(w, "Unauthorized.", 401)
				return
			}
		}
		fn(w, r)
	}
}

func check(u, p string) bool {
	if u == c.Auth.Username && p == c.Auth.Password {
		return true
	}
	return false
}


func main() {

	http.HandleFunc("/", auth(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", auth(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)
	mutex := sync.Mutex{}
	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
			}
			mutex.Lock()
			res[check.Name()] = ResultReturn{
				Success: s,
				Data: data,
			}
			mutex.Unlock()
		}(c)
	}
	wg.Wait()

	return res, globaleResult
}