package auth2

import (
	"net/http"
	"strings"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/globals"
)

type Context struct {
	accessUUID string
	w          http.ResponseWriter
	r          *http.Request
	// mapData    map[interface{}]interface{}
}

func NewContext(w http.ResponseWriter, r *http.Request) (ctx *Context) {
	ctx = &Context{
		w:          w,
		r:          r,
		accessUUID: utils.GetUUID(),
	}
	globals.SugarLogger.Debugf("NewContext ip:%s", ctx.GetRealRemoteIP())
	return ctx
}

func (ctx *Context) GetResponseWriter() http.ResponseWriter {
	return ctx.w
}

func (ctx *Context) GetRequest() *http.Request {
	return ctx.r
}

func (ctx *Context) GetTrackInfo() string {
	return ctx.accessUUID
}

func (ctx *Context) GetRealRemoteIP() (ip string) {
	r := ctx.r
	if r != nil {
		// globals.SugarLogger.Debugf("GetRealRemoteIP header:%s", utils.Format4Output(r.Header, false))
		ip = r.Header.Get("X-Forwarded-For")
		if ip == "" {
			ip = r.Header.Get("X-real-ip")
		}
		if ip == "" {
			ip = strings.Split(r.RemoteAddr, ":")[0]
		} else {
			ip = strings.Split(ip, ",")[0]
		}
	}
	return ip
}
