// ************************************
// @package: websocketServer
// @description: websocket服务端
// @author:
// @revision history:
// @create date: 2022-02-15 14:10:51
// ************************************
package websocketServer

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

type WsServer struct {
	*webServer.HttpServer

	// websocket连接管理
	*connManager
}

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

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

func NewWsServer(addr string, isCheckIP bool) (server *WsServer) {
	server = &WsServer{
		HttpServer: webServer.NewHttpServer(addr, isCheckIP),
		connManager: &connManager{
			upgrader: &websocket.Upgrader{},
			allConns: make(map[*websocket.Conn]*Context),
		},
	}

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

	return
}

func NewWsServer2(addr string, webServerObj webServer.IWebServer) (server *WsServer) {
	server = &WsServer{
		HttpServer: webServer.NewHttpServer2(addr, webServerObj),
		connManager: &connManager{
			upgrader: &websocket.Upgrader{},
			allConns: make(map[*websocket.Conn]*Context),
		},
	}

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

	return
}

func NewWsServer3(addr string, isCheckIP bool, readTimeout time.Duration, readHeaderTimeout time.Duration, writeTimeout time.Duration) (server *WsServer) {
	server = &WsServer{
		HttpServer: webServer.NewHttpServer3(addr, isCheckIP, readTimeout, readHeaderTimeout, writeTimeout),
		connManager: &connManager{
			upgrader: &websocket.Upgrader{},
			allConns: make(map[*websocket.Conn]*Context),
		},
	}

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

	return
}
