package app

import (
	"common/log"
	"common/net/socket/websocket"
	"fmt"
	"gateway/config"
	"gateway/internal/net/ws_gateway"
	"github.com/panjf2000/gnet/v2"
	"sync"
	"time"
)

// ModuleWebsocketServer Websocket服务模块
type ModuleWebsocketServer struct {
	wg     *sync.WaitGroup
	server *websocket.WSServer
}

func (m *ModuleWebsocketServer) init() error {
	m.wg = &sync.WaitGroup{}
	m.server = websocket.NewWSServer(
		&ws_gateway.GatewayWsServer{},
		log.GetLogger().Named("ws_server"),
		5*time.Second,
	)
	return nil
}

func (m *ModuleWebsocketServer) start() error {
	m.wg.Add(1)
	go func() {
		defer m.wg.Done()
		_ = m.server.Run(
			fmt.Sprintf("tcp4://0.0.0.0:%v", config.Get().Serve.Socket.Web.Port),
			true,
			0,
			gnet.TCPNoDelay,
			64*1024,
			64*1024,
			true,
			false,
			true,
			log.GetLogger().Named("GNET"),
		)
	}()
	return nil
}

func (m *ModuleWebsocketServer) stop() error {
	if err := m.server.Stop(); err != nil {
		log.Errorf("stop websocket server failed: %v", err)
	}
	m.wg.Wait()
	return nil
}
