package socket_io

import (
	"crm-api/pkg/lfshook"

	socketio "github.com/googollee/go-socket.io"
)

var SocketIOServer *socketio.Server

func StartSocketIO() {
	lfshook.NewLogger().Info("Start SocketIO")
	SocketIOServer = socketio.NewServer(nil)

	SocketIOServer.OnConnect("/", func(s socketio.Conn) error {
		s.SetContext("")
		//!TODO check token
		// lfshook.NewLogger().Infof("socketio query %s", s.URL().RawQuery)
		// lfshook.NewLogger().Infof("socket.io connected id: %s", s.ID())
		return nil
	})

	SocketIOServer.OnEvent("/", "chat", func(s socketio.Conn, msg string) {
		lfshook.NewLogger().Infof("chat: %s", msg)
		s.Emit("reply", "have "+msg)
	})

	SocketIOServer.OnEvent("/", "bye", func(s socketio.Conn) string {
		last := s.Context().(string)
		s.Emit("bye", last)
		s.Close()
		return last
	})

	SocketIOServer.OnError("/", func(s socketio.Conn, e error) {
		lfshook.NewLogger().Infof("meet error: %+v", e)
	})

	SocketIOServer.OnDisconnect("/", func(s socketio.Conn, reason string) {
		lfshook.NewLogger().Infof("closed %+v", reason)
	})

	go SocketIOServer.Serve()
}
