package main

import (
	"fmt"
	"git.swzry.com/zry/go-hhc-cli/hhc_mangekyo"
	"git.swzry.com/zry/go-hhc-cli/hhc_telws"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"github.com/tjfoc/gmsm/sm2"
	"net/http"
	"os"
	"time"
)

var ListenAddress string

var TestSM2KeyPair *sm2.PrivateKey

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

func main() {
	//runtime.Breakpoint()
	ListenAddress = os.Getenv("listen")
	if ListenAddress == "" {
		fmt.Println("No environment variable 'listen', use default value ':9090'")
		ListenAddress = ":9090"
	}
	k, err := sm2.GenerateKey()
	if err != nil {
		fmt.Println("Failed Generate SM2 Key:", err)
		return
	}
	TestSM2KeyPair = k
	r := gin.Default()
	r.GET("/api/app-config.satori", appConfig)
	telwsGrp := r.Group("/api/telws/")
	muh := NewMUH()
	mhf := hhc_mangekyo.NewMangekyoHandlerFactory(muh)
	cbh := hhc_telws.NewCliBackendHandler(telwsGrp, mhf)
	err = cbh.InitSecure(time.Minute * 10)
	if err != nil {
		fmt.Println("Failed Init Telws Handler:", err)
		return
	}
	sah := hhc_telws.NewTelwsAuthSimpleAAA()
	sah.SimpleAAAAddSimple("admin", "114514", 4)
	cbh.AddAuthHandler(sah)
	r.Run(ListenAddress)
}

func appConfig(ctx *gin.Context) {
	ctx.JSON(200, gin.H{
		"title":              "Hypothetical Swtich",
		"appBarColor":        "#1c2c61",
		"telwsUrl":           "/api/telws/",
		"projectName":        "Hypothetical Switch",
		"projectDescription": "A hypothetical switch CLI interface for HHC_CLI demo.",
	})
}
