package main

import (
	"fmt"
	logging "github.com/ipfs/go-log/v2"
	"github.com/urfave/cli/v2"
	"google.golang.org/grpc"
	"net"
	"os"
	"wallet-server/conf"
	"wallet-server/dao"
	"wallet-server/service"
)

var log = logging.Logger("main")

func main() {
	_ = logging.SetLogLevel("*", "INFO")

	app := cli.App{
		Name:  "wallet-server",
		Usage: "eth and tron wallet service",
		Commands: []*cli.Command{
			runCmd,
		},
		EnableBashCompletion: true,
	}

	if err := app.Run(os.Args); err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: %s\n\n", err)
		os.Exit(1)
	}
}

var runCmd = &cli.Command{
	Name:  "run",
	Usage: "run wallet server process",
	Flags: []cli.Flag{
		&cli.StringFlag{
			Name:  "listen",
			Usage: "The host address and port on which the key manager will listen",
			Value: "127.0.0.1:6667",
		},
		&cli.StringFlag{
			Name:  "config",
			Usage: "config file path",
		},
	},
	Action: func(cctx *cli.Context) error {
		err := conf.InitConfig(cctx.String("config"))
		if err != nil {
			return err
		}
		db, err := dao.InitMysqlDB()
		if err != nil {
			return err
		}

		listen := cctx.String("listen")
		listener, err := net.Listen("tcp", listen)
		if err != nil {
			return err
		}

		log.Infof("grpc server Listing on: %s", listen)

		grpcServer := grpc.NewServer()
		server, err := service.NewWalletServer(db)
		if err != nil {
			return err
		}

		service.RegisterWalletServerServer(grpcServer, server)
		if err = grpcServer.Serve(listener); err != nil {
			log.Error(err)
			return err
		}

		return nil
	},
}
