package main

import (
	"flag"
	"fmt"
	"pay/api"
	"pay/bus"
	"pay/conf"
	"pay/db"
	"pay/log"
	"pay/pay"

	"infish.cn/comm"

	"go.uber.org/dig"
)

var confFile = flag.String("conf", "./app.yaml", "conf file")
var natsUrl = flag.String("nats", "", "nats url config")
var port = flag.Int("port", 0, "http port monitor")

func BuildApp() *dig.Container {

	app := dig.New()
	_ = app.Provide(func() (*conf.AppConf, error) {
		c, err := conf.NewAppConf(*confFile)
		if err == nil {
			if *port > 0 {
				c.Port = int32(*port)
			}
			if len(*natsUrl) > 0 {
				c.Nats.Url = *natsUrl
			}
		}
		fmt.Println(*natsUrl, *port)
		return c, err
	})
	_ = app.Provide(bus.NewNatsBus)
	_ = app.Provide(db.NewConfigMongoDB)
	_ = app.Provide(db.NewConfigRedisClient)
	_ = app.Provide(api.NewHttpService)
	// 支付宝、微信初始化
	_ = app.Provide(pay.NewPay)

	return app
}

func main() {

	flag.Parse()
	app := BuildApp()

	err := app.Invoke(func(svc *api.Service, nats *comm.NatsBus, pay *pay.Pay) error {
		go pay.Connect()
		go nats.Run(nil)
		svc.Run()
		return nil
	})

	if err != nil {
		log.Errorf("the pink service start fail %+v", err)
		panic(err)
	}
}
