package proxy

import (
	. "gateway/common/gatecode"
	"gateway/common/logs"
	"gateway/core/node"
	"gateway/core/proxy/broker"
	"gateway/core/proxy/middleware"
	"gateway/core/proxy/router"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gctx"
	"net/http/httputil"
	"net/url"
)

var bManager = broker.InitBroker()
var routerManager *router.Manager

// InitGateWayServer 初始化网关服务
func InitGateWayServer() *ghttp.Server {
	//创建节点,并持续观察节点变化
	watchNode := node.NewNode()
	go watchNode.NewWatcher(gctx.New(), bManager)

	//初始化可访问路由
	var err error
	routerManager, err = router.InitRouterManager()
	if err != nil {
		logs.GInfo.Error(gctx.New(), err)
	}

	gateWayServer := g.Server()
	//关闭系统自带请求日志
	gateWayServer.SetLogger(logs.GInfo)
	gateWayServer.SetErrorLogEnabled(false)

	//注册中间件
	gateWayServer.Use(middleware.ErrorHandler) //错误拦截
	gateWayServer.Use(func(r *ghttp.Request) {
		r.SetError(routerManager.InfusionContext(r)) //context注入全局信息
		r.Middleware.Next()
	})
	gateWayServer.Use(middleware.FilterHandler) //权限过滤
	//注册代理
	gateWayServer.BindHandler("POST:/*", proxyHandler)
	return gateWayServer
}

// proxyHandler 网关代理Handler处理，完成所有校验
var proxyHandler = func(r *ghttp.Request) {
	if r.GetError() != nil {
		return
	}
	gCtx := router.GetGContext(r.GetCtx())
	//获取服务地址
	proxyAddr, err := bManager.GetServerAddr(gCtx.RouterRule.MiddleCode)
	if err != nil {
		r.SetError(err)
		return
	}
	//代理地址存入ctx中
	gCtx.ServerAddr = proxyAddr
	router.UpdateGContext(r, gCtx)
	//调用请求
	proxyUrl, err := url.Parse(proxyAddr)
	if err != nil {
		r.SetError(NewErrorWithCode(GATEWAY_REGISTED_URL_ERR, err.Error()))
		// WillDo:后续异常节点冻结
		return
	}
	httputil.NewSingleHostReverseProxy(proxyUrl).ServeHTTP(r.Response.ResponseWriter, r.Request)
}
