package websocketServer

import (
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
	webServer "Framework/webServer"
	"strconv"
	"sync"
	"testing"
	"time"
)

// 处理HTTP请求
func httpHandler(cxt *webServer.Context) {
	msg := "test msg"
	cxt.GetResponseWriter().Write([]byte(msg))
}

// websocket连接事件
func onConnFunc(ctx *Context) {
	fmt.Printf("new conn, ip: %s %p\n", ctx.GetWebServerContext().GetRequestIP(), ctx)
	ctx.SendMessage(websocket.TextMessage, []byte("Hello")) // 返回数据
}

// websocket关闭事件
func onCloseFunc(ctx *Context) {
	fmt.Printf("close conn, ip: %s %p\n", ctx.GetWebServerContext().GetRequestIP(), ctx)
}

// websocket接收事件
func onMsgFunc(ctx *Context, msgType int, msgData []byte) {
	fmt.Printf("%p ", ctx)
	fmt.Println("msg ip:", ctx.GetWebServerContext().GetRequestIP(), "msg type:", msgType, "msg:", string(msgData))
	ctx.SendMessage(msgType, []byte("SVR: "+string(msgData))) // 返回数据

	// 主动关闭连接测试
	if string(msgData) == "close" {
		ctx.SendMessage(msgType, []byte("close")) // 返回数据
		//time.Sleep(time.Microsecond * 100)
		ctx.Close()
	}
}

func TestWsServer(t *testing.T) {
	var ssl bool = false
	var server IServer
	if ssl {
		server = NewWssServer(":22222", "cert.pem", "key.pem", false)
	} else {
		server = NewWsServer(":22222", false)
	}

	server.SetIfDelegate(false)

	// 注册HTTP处理函数
	server.RegisterHandler("/http", httpHandler, &webServer.HandlerConfig{})

	// 设置websocket允许跨域访问
	server.GetUpgrader().CheckOrigin = func(r *http.Request) bool {
		return true
	}
	//upgrader := &websocket.Upgrader{
	//	// 允许跨域
	//	CheckOrigin: func(r *http.Request) bool {
	//		return true
	//	},
	//}
	//server.SetUpgrader(upgrader)

	// 注册websocket处理事件
	server.RegisterWebsocketHandler("/websocket", &EventCallbackFuncs{
		OnConnFunc:  onConnFunc,
		OnCloseFunc: onCloseFunc,
		OnMsgFunc:   onMsgFunc,
	}, &webServer.HandlerConfig{})

	// 设置广播并发数
	server.SetBroadcastConcurrent(2)

	// 设置接收到Ping消息时，自动回复Pong信息
	server.SetAutoPong(true)

	// 设置心跳检测信息（心跳检测周期10秒；缺少2个心跳周期断开连接）
	server.SetHeartbeatDetectInfo(2, time.Second*10)

	// 广播测试
	go func() {
		var i = 0
		for {
			time.Sleep(time.Second * 10)
			// 广播测试
			server.BroadcastMessage(websocket.TextMessage, []byte(strconv.Itoa(i)))
			i++
		}
	}()

	wg := sync.WaitGroup{}
	server.Start(&wg)
}
