package main

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

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

const (
	version = "1.0.0"
	website = "https://www.overflow.cloud"
	banner  = `

 ██████╗ ██╗   ██╗███████╗██████╗ ███████╗██╗      ██████╗ ██╗    ██╗
██╔═══██╗██║   ██║██╔════╝██╔══██╗██╔════╝██║     ██╔═══██╗██║    ██║
██║   ██║██║   ██║█████╗  ██████╔╝█████╗  ██║     ██║   ██║██║ █╗ ██║
██║   ██║╚██╗ ██╔╝██╔══╝  ██╔══██╗██╔══╝  ██║     ██║   ██║██║███╗██║
╚██████╔╝ ╚████╔╝ ███████╗██║  ██║██║     ███████╗╚██████╔╝╚███╔███╔╝
 ╚═════╝   ╚═══╝  ╚══════╝╚═╝  ╚═╝╚═╝     ╚══════╝ ╚═════╝  ╚══╝╚══╝ 
                                                                     
`
)

func printVersion() {
	log.Printf("Version: %s\n", version)
	log.Printf("Url: %s\n", website)
	log.Println(banner)
}

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.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)

	if err := http.ListenAndServe(addr, nil); err != nil {
		log.Fatal(err)
	}
}

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()
}
