package main

import (
	"fmt"
	"os"

	"code.wuban.net.cn/multisend"
	"github.com/spf13/cobra"
)

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

var (
	rate, sendPeriod, count, expectedTime int
	websocketAddr, redisAddr, redisPasswd string
	sendTxPrivateKey                      string
	webStaticDir                          string
)

func init() {
	//cobra.OnInitialize(initConfig)
	rootCmd.PersistentFlags().StringVar(&websocketAddr, "websocketAddr", "ws://13.40.31.153:8546", "eth classical websocket rpc addr")
	rootCmd.PersistentFlags().IntVar(&rate, "rate", 1, "every period send tx number")
	rootCmd.PersistentFlags().IntVar(&sendPeriod, "sendPeriod", 3, "send tx time unit")
	rootCmd.PersistentFlags().IntVar(&count, "count", 1000, "total tx number")
	rootCmd.PersistentFlags().IntVar(&expectedTime, "expectedTime", 3600, "the  expected time used to send the total tx number")
	rootCmd.PersistentFlags().StringVar(&redisAddr, "redisAddr", "127.0.0.1:6379", "commit the  original txs to the redis queue")
	rootCmd.PersistentFlags().StringVar(&redisPasswd, "redisPasswd", "redis20220217", "redis password")
	rootCmd.PersistentFlags().StringVar(&sendTxPrivateKey, "sendTxPrivateKey", "a1994419e9b06a7b27e8d094840ae26a6b7806633bb8be55a1a835f1620d8cec", "send tx to the chain with the private key")
	rootCmd.PersistentFlags().StringVar(&webStaticDir, "webStaticDir", "./static/", "front end page")
}

var rootCmd = &cobra.Command{
	Use:   "sendTxs",
	Short: "send batch txs hash to chain and original txs to redis",
	Run: func(cmd *cobra.Command, args []string) {
		//go func() {
		//	if err := multisend.ProduceOriginalTx(); err != nil {
		//		panic(err)
		//	}
		//}()

		fmt.Printf("webStaticDir:  %s \n", webStaticDir)

		cfg := multisend.Config{
			Rate:             rate,
			Count:            count,
			Connections:      1,
			Time:             expectedTime,
			SendPeriod:       sendPeriod,
			ClientFactory:    "ethclient",
			SendTxPrivateKey: sendTxPrivateKey,
			WebStaticDir:     webStaticDir,
		}

		transactor, err := multisend.NewTransactor(websocketAddr, &cfg)

		if err != nil {
			panic(err)
		}

		transactor.Start()

		go func() {
			w := multisend.WebServicer{}
			if err := w.WebService(cfg); err != nil {
				panic(err)
			}

		}()

		multisend.Start(redisAddr, redisPasswd)

	},
}
