// ************************************
// @package: websocketServer
// @description: websocket加密服务端
// @author:
// @revision history:
// @create date: 2022-02-15 16:18:45
// ************************************
package websocketServer

import (
	"github.com/gorilla/websocket"
	webServer "Framework/webServer"
)

type WssServer struct {
	*webServer.HttpsServer

	// websocket连接管理
	*connManager
}

// RegisterWebsocketHandler
// @description: 注册websocket回调
// parameter:
//
//	@receiver ws:
//	@path:注册的访问路径
//	@handlerFuncObj:回调方法
//	@configObj:Handler配置对象
//
// return:
func (wss *WssServer) RegisterWebsocketHandler(path string, eventCallback *EventCallbackFuncs, configObj *webServer.HandlerConfig) {
	wss.RegisterHandlerWithUserData(path, hookHandler, configObj, &userDatas{
		server:        wss,
		eventCallback: eventCallback,
	})
}

// RegisterRegexWebsocketHandler
// @description: 注册正则websocket回调
// parameter:
//
//	@receiver wss:
//	@path:注册的正则访问路径
//	@eventCallback:回调方法
//	@configObj:Handler配置对象
//
// return:
func (wss *WssServer) RegisterRegexWebsocketHandler(path string, eventCallback *EventCallbackFuncs, configObj *webServer.HandlerConfig) {
	wss.RegisterRegexHandlerWithUserData(path, hookHandler, configObj, &userDatas{
		server:        wss,
		eventCallback: eventCallback,
	})
}

func NewWssServer(addr, certFileName, keyFileName string, isCheckIP bool) (server *WssServer) {
	server = &WssServer{
		HttpsServer: webServer.NewHttpsServer(addr, certFileName, keyFileName, isCheckIP),
		connManager: &connManager{
			upgrader: &websocket.Upgrader{},
			allConns: make(map[*websocket.Conn]*Context),
		},
	}

	// 开启心跳检测协程
	server.connManager.heartbeatDetect()

	return
}

func NewHttpsServer2(addr, certFileName, keyFileName string, webServerObj webServer.IWebServer) (server *WssServer) {
	server = &WssServer{
		HttpsServer: webServer.NewHttpsServer2(addr, certFileName, keyFileName, webServerObj),
		connManager: &connManager{
			upgrader: &websocket.Upgrader{},
			allConns: make(map[*websocket.Conn]*Context),
		},
	}

	// 开启心跳检测协程
	server.connManager.heartbeatDetect()

	return
}
