package main

import (
	"log"
	"net/http"
	"os"
	"path/filepath"

	"git.loafle.net/overflow/overflow_service_websocket/config"
	"git.loafle.net/overflow/overflow_service_websocket/protocol/jsonrpc"
	"git.loafle.net/overflow/overflow_service_websocket/server"
)

func main() {

	// Initialize config
	config := loadConfig()

	addr := config.Server.Addr
	useTLS := config.Server.Tls
	sConfig := server.NewOptions(&config.Websocket)
	// Print banner
	printVersion()

	// Config TLS

	ws := server.New(sConfig)
	ws.RegistProtocol("jsonrpc", jsonrpc.NewHandler())
	ws.OnConnection(func(c server.Client) {
		log.Println("Client have been connected")
		c.OnDisconnect(func(c server.Client) {
			log.Println("Client have been disconnected")
		})
	})

	http.Handle("/rpc", ws.HTTPHandler())
	log.Printf("Address: %s, UseTLS: %t", addr, useTLS)

	http.ListenAndServe(addr, nil)

}

func loadConfig() *config.Config {
	os.Chdir("./")
	wd, _ := os.Getwd()
	path := filepath.Join(wd, "config.json")

	err := config.InitConfig(path)
	if nil != err {
		log.Fatalln("Config error")
	}
	return config.GetConfig()
}
