package admin

import (
	"errors"
	"net/http"
	"os"
	"runtime"

	"git.pyer.club/kingecg/gohttpd/model"
	"git.pyer.club/kingecg/gohttpd/server"
)

type RunStatus struct {
	Goroutines int `json:"goroutines"`
}

func about(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("About Page"))

}

func setConfig(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	ctxData := ctx.Value(server.RequestCtxKey("data")).(map[string]interface{})
	data, ok := ctxData["data"]
	if !ok {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	t := data.(model.HttpServerConfig)
	if t.Name == "admin" {
		w.WriteHeader(http.StatusForbidden)
		resp := server.NewErrorResult(errors.New("不能通过api设置管理服务器"))
		w.Write(resp)
	}
	err := model.SetServerConfig(&t)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write(server.NewErrorResult(err))
		return
	}
	defer func() {
		os.Exit(0)
	}()
	w.WriteHeader(http.StatusOK)
	w.Write(server.NewSuccessResult(t))
}

func getServerConfigure(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	ctxData := ctx.Value(server.RequestCtxKey("data")).(map[string]interface{})
	id, ok := ctxData["id"]
	if ok {
		if id.(string) == "admin" {
			w.WriteHeader(http.StatusForbidden)
			resp := server.NewErrorResult(errors.New("不能通过api获取管理服务器配置信息"))
			w.Write(resp)
			return
		}
		data := model.GetServerConfig(id.(string))
		///	configContent, _ := json.Marshal(data)
		w.WriteHeader(http.StatusOK)
		w.Write(server.NewSuccessResult(data))
	} else {
		http.NotFound(w, r)
	}
}

func getStatus(w http.ResponseWriter, r *http.Request) {
	//获取当前进程的goroutines数量
	ret := RunStatus{
		Goroutines: runtime.NumGoroutine(),
	}

	w.WriteHeader(http.StatusOK)
	w.Write(server.NewSuccessResult(ret))
}

var AdminServerMux *server.RestMux

func init() {
	AdminServerMux = server.NewRestMux("/api")
	AdminServerMux.Use(server.JwtAuth)
	AdminServerMux.HandleFunc("GET", "/about", http.HandlerFunc(about))
	postConfigRoute := AdminServerMux.HandleFunc("POST", "/config", http.HandlerFunc(setConfig))
	postConfigRoute.Add(server.Parse[model.HttpServerConfig])
	AdminServerMux.HandleFunc("GET", "/config/:id", http.HandlerFunc(getServerConfigure))
	AdminServerMux.HandleFunc("GET", "/status", http.HandlerFunc(getStatus))
	loginRoute := AdminServerMux.HandleFunc("POST", "/login", http.HandlerFunc(login))
	loginRoute.Add(server.Parse[LoginModel])
	// AdminServerMux.Use(server.BasicAuth)
}
