package main

import (
	"log"
	"os"
	"strconv"

	"git.pyer.club/kingecg/command"
	"git.pyer.club/kingecg/gotunnelserver/client"
	"git.pyer.club/kingecg/gotunnelserver/util"
)

type TunnelAgent struct {
	Username string `flag_default:"tcclient" flag_usage:"username for tunnel server"`
	Salt     string `flag_default:"" flag_usage:"salt for tunnel server"`
	Address  string `flag_default:"ws://127.0.0.1:8080" flag_usage:"address for tunnel server"`
}

var (
	cmdClient *client.CommandClient
	dataEp    *client.DataEndPoint
)

func main() {
	cargs := new(TunnelAgent)
	v, _ := command.NewFVSet(cargs)
	err := command.Parse(os.Args[1:], v)
	if err != nil {
		os.Exit(0)
		return
	}
	clientConfig := &client.ClientConfig{
		Username: cargs.Username,
		Salt:     cargs.Salt,
		Address:  cargs.Address,
	}
	cmdClient = client.NewAgent(clientConfig)
	cmdClient.On(util.CmdTypeMap[util.ConnectInited], func(args ...interface{}) {
		playload, _ := args[0].(map[string]string)
		sessionId := playload["sessionId"]
		dataEp = client.NewDataEndPoint(cmdClient, sessionId)
		dataEp.Host = playload["host"]
		dataEp.Port, _ = strconv.Atoi(playload["port"])
		log.Println("connect inited:", sessionId, dataEp.Host, dataEp.Port)
		go dataEp.Connect()
	})
	cmdClient.On(util.CmdTypeMap[util.ErrorCmd], func(args ...interface{}) {
		playload, _ := args[0].(map[string]string)
		log.Println("error:", playload["error"])
		os.Exit(1)
	})
	defer func() {
		if r := recover(); r != nil {
			log.Println(r)
			return
		}
	}()
	cmdClient.Start()
}
