package middleware

import (
	"blazing/modules/base/config"
	"fmt"
	"net/http"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/lxzan/gws"
)

func MiddlewareCORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	corsOptions := r.Response.DefaultCORSOptions()
	corsOptions.AllowDomain = []string{"*", "localhost", "tauri.localhost"}
	if !r.Response.CORSAllowedOrigin(corsOptions) {
		r.Response.WriteStatus(http.StatusForbidden)
		return
	}
	r.Response.CORS(corsOptions)
	if r.Response.Request.Method == "OPTIONS" {
		r.Response.WriteStatus(http.StatusOK)
		return
	}
	//	fmt.Println(r.Response.Header())
	//g.Dump(r.Response.Server.SetConfig(gtt))
	//r.Response.Header().Del("Server") // 删除Server头
	//	r.Response.Header().Set("Server", "blazing")
	r.Middleware.Next()
}
func init() {
	if config.Config.Middleware.Authority.Enable {
		g.Server().BindMiddleware("/admin/*/open/*", BaseAuthorityMiddlewareOpen)
		g.Server().BindMiddleware("/admin/*/comm/*", BaseAuthorityMiddlewareComm)
		g.Server().BindMiddleware("/admin/*", BaseAuthorityMiddleware)
		g.Server().BindMiddleware("/*", AutoI18n)
		g.Server().BindMiddleware("/*", MiddlewareCORS)

	}
	if config.Config.Middleware.Log.Enable {
		g.Server().BindMiddleware("/admin/*", BaseLog)
	}
	g.Server().BindHandler("/ws/*", func(r *ghttp.Request) {
		urls := r.URL.Query().Get("port")
		fmt.Println(urls)
		tt := new(Handler)

		tt.port = gconv.Int(urls)
		upgrader := gws.NewUpgrader(tt, &gws.ServerOption{
			//CompressEnabled: true,

			// 在querystring里面传入用户名
			// 把Sec-WebSocket-Key作为连接的key

			// 刷新页面的时候, 会触发上一个连接的OnClose/OnError事件, 这时候需要对比key并删除map里存储的连接
			Authorize: func(rt *http.Request, session gws.SessionStorage) bool {
				//r.s\\\
				//	r.Get("t")
				//admin := cool.GetAdmin(r.Context())
				// var name = r.URL.Query().Get("name")
				// if name == "" {
				// 	return false
				// }
				//	t, _ := service.NewBaseSysUserService().Person(admin.UserID)

				//Loger.Debug(context.TODO(), t.Mimi)
				//	session.Store("name", t.Mimi)
				//session.Store("key", r.Header.Get("Sec-WebSocket-Key"))
				return true
			},
		})

		socket, err := upgrader.Upgrade(r.Response.Writer, r.Request)
		if err != nil {
			fmt.Println(err)
			return
		}
		// ants.Submit(func() {
		// 	socket.ReadLoop()
		// })
		//	ants.Submit(func() { socket.ReadLoop() })
		go socket.ReadLoop()

	})
}
