package main

import (
	"encoding/json"
	"net/http"
	"os"

	"git.pyer.club/kingecg/gohttpd/admin"
	"git.pyer.club/kingecg/gohttpd/model"
	"git.pyer.club/kingecg/gohttpd/server"
	"git.pyer.club/kingecg/gohttpd/utils"
	"git.pyer.club/kingecg/gologger"
)

type GoHttp struct {
	logger gologger.Logger
}

func (g *GoHttp) Start() {
	conf := model.GetConfig()
	g.logger = gologger.GetLogger("Server")
	g.logger.Info("start gohttpd")
	// if g.conf != nil {
	adminHandler := server.NewServeMux(conf.Admin)
	adminHandler.Handle("/api/", http.StripPrefix("/api", admin.AdminServerMux))
	g.makeServer(conf.Admin, adminHandler)

	for _, s := range conf.Servers {
		sHandler := server.NewServeMux(s)
		g.makeServer(s, sHandler)
	}

	for _, listener := range server.ServerManager {
		listener.Start()
		listener.Serve()

	}
	g.logger.Info("gohttpd start success")
}

func (g *GoHttp) makeServer(conf *model.HttpServerConfig, mux http.Handler) {
	s := &http.Server{
		Handler: mux,
	}
	name := conf.Name
	port := conf.Port
	ss := &server.Server{
		Server: s,
		Conf:   conf,
	}
	server.AddServer(name, ss, port)
}

func (g *GoHttp) Stop() {}

func LoadConfig() {
	cpath := utils.NormalizePath("./config.json")

	// read content from cpath
	content, _ := os.ReadFile(cpath)
	json.Unmarshal(content, &model.Config)
	//normalize path in config
	for _, appender := range model.Config.Logging.Appenders {
		if appender.Type == "file" {
			appender.Options["file"] = utils.NormalizePath(appender.Options["file"].(string))
		}
	}
	normalizeServer(model.Config.Admin)
	for _, server := range model.Config.Servers {
		normalizeServer(server)
	}
	gologger.Configure(model.Config.Logging)
	logger := gologger.GetLogger("Server")
	logger.Info("Load config success")
}

func normalizeServer(server *model.HttpServerConfig) {
	for index, path := range server.Paths {
		if path.Root != "" {
			server.Paths[index].Root = utils.NormalizePath(path.Root)
		}
	}
	if server.CertFile != "" {
		server.CertFile = utils.NormalizePath(server.CertFile)
	}
	if server.KeyFile != "" {
		server.KeyFile = utils.NormalizePath(server.KeyFile)
	}
}
