package server

import (
	"net/http"
	"strconv"

	"git.pyer.club/kingecg/gologger"
	config "git.pyer.club/kingecg/gosocketio/config"
	json "git.pyer.club/kingecg/gosocketio/json"
	socketio "github.com/googollee/go-socket.io"
)

var server *socketio.Server

func Luanch() {

	logger := gologger.GetLogger("server")
	configObj := config.GetConfig()
	host := configObj.Host
	port := configObj.Port
	logger.Debug("socket.io server is about to run on " + host + ":" + strconv.Itoa(port))
	server = socketio.NewServer(nil)
	server.OnConnect("/", func(s socketio.Conn) error {
		s.SetContext("")
		logger.Debug("/ connected:", s.ID())
		return nil
	})
	server.OnConnect(configObj.NameSpace, func(s socketio.Conn) error {
		s.SetContext("")
		logger.Debug("connected:", s.ID())
		s.Emit("connect")
		return nil
	})
	server.OnEvent(configObj.NameSpace, "join room", func(s socketio.Conn, msg string) {
		var jsonObj = json.JSONObject{}
		jsonObj.UnmarshalJSON([]byte(msg))
		logger.Debug("join room:", jsonObj.Get("did"))
		s.Join(jsonObj.Get("did").(string))
		s.Emit("join success", "have "+msg)
	})
	go server.Serve()
	defer server.Close()

	http.Handle(configObj.Path, server)
	error := http.ListenAndServe(host+":"+strconv.Itoa(port), nil)
	if error != nil {
		logger.Error("http server start error:", error)
	}
}
