package server_webSocket

import (
	"fmt"
	"net/http"
	"sync"

	"common/clientMgr"
	"github.com/gorilla/websocket"
	"goutil/debugUtil"
	"goutil/logUtil"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func handleConn(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)

	//是否debug模式
	if debugUtil.IsDebug() {
		logUtil.DebugLog(fmt.Sprintf("收到客户的websockte连接,ip%v", conn.RemoteAddr()))
	}

	if err != nil {
		logUtil.ErrorLog("websocket.handleConn获取连接出错，err:%v", err)
		return
	}

	// 创建客户端对象
	clientObj := newClient(conn)
	clientObj.start()
	clientMgr.RegisterClient(clientObj)

	debugUtil.Printf("收到连接请求:remoteAdd:%s\n", conn.RemoteAddr())
}

// Start 启动服务器
func Start(wg *sync.WaitGroup, address string, isUseTSL bool) {
	defer wg.Done()

	msg := fmt.Sprintf("server_websocket begins to listen on:%s...", address)
	fmt.Println(msg)
	logUtil.InfoLog(msg)

	http.HandleFunc("/", handleConn)
	if isUseTSL {
		err := http.ListenAndServeTLS(address, "tlsFile/7qule.com.pem", "tlsFile/7qule.com.key", nil)
		if err != nil {
			panic(fmt.Sprintf("server_websocket.ListenAndServeTLS, err:%v", err))
		}
	} else {
		err := http.ListenAndServe(address, nil)
		if err != nil {
			panic(fmt.Sprintf("server_websocket.ListenAndServe, err:%v", err))
		}
	}
}
