package midware

import (
	"net/http"
	"strings"

	"be.ems/lib/log"
	"be.ems/lib/services"
	tokenConst "be.ems/src/framework/constants/token"
	"github.com/gorilla/mux"
)

func LoggerTrace(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Do stuff here
		log.Trace("Http Trace Info:")
		log.Trace("	From Host:", r.RemoteAddr)
		log.Trace("	To Host:", r.Host)
		log.Debug("	RequestUri:", r.RequestURI)
		log.Trace("	Method:", r.Method)
		log.Trace("	Proto:", r.Proto)
		log.Trace("	ContentLength:", r.ContentLength)
		log.Trace("	User-Agent:", r.Header.Get("User-Agent"))
		log.Trace("	Content-Type:", r.Header.Get("Content-Type"))
		log.Trace("	AccessToken:", r.Header.Get("AccessToken"))
		log.Trace("	Authorization:", r.Header.Get(tokenConst.HEADER_KEY))
		log.Trace("Trace End=====")
		//body, _ := io.ReadAll(io.LimitReader(r.Body, global.RequestBodyMaxLen))
		// nop-close to ready r.Body !!!
		//r.Body = ioutil.NopCloser(bytes.NewReader(body))
		//log.Trace("Body:", string(body))
		// Call the next handler, which can be another middleware in the chain, or the final handler.
		// if r.Method == "OPTIONS" {
		// 	services.ResponseStatusOK201Accepted(w)
		// 	return
		// }

		next.ServeHTTP(w, r)
	})
}

// 已禁用
func OptionProcess(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "OPTIONS" {
			services.ResponseStatusOK201Accepted(w)
			return
		}

		next.ServeHTTP(w, r)
	})
}

// 已禁用
func CheckPermission(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("AccessToken")
		vars := mux.Vars(r)
		management := vars["managedType"]
		element := vars["elementTypeValue"]
		object := vars["objectTypeValue"]
		pack := "*"
		if token != "" && element != "oauth" {
			log.Debugf("token:%s, method:%s, management:%s, element:%s, object:%s, pack:%s", token, r.Method, management, element, object, pack)
			exist, err := services.CheckUserPermission(token, strings.ToLower(r.Method), management, element, object, pack)
			if err != nil {
				log.Error("Failed to get permission:", err)
				services.ResponseForbidden403NotPermission(w)
				return
			}
			if !exist {
				log.Error("Not permission!")
				services.ResponseForbidden403NotPermission(w)
				return
			}
		}
		next.ServeHTTP(w, r)
	})
}
