package app

import (
	"common/log"
	"common/net/socket/websocket"
	"fmt"
	"gateway/config"
	"gateway/net/ws_gateway"
	"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(
			log.GetLogger().Named("GNET"),
			fmt.Sprintf("tcp4://0.0.0.0:%v", config.Get().Serve.Socket.Web.Port),
			true,
			true,
			false,
			false,
			true,
			8,
		)
	}()
	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
}
