package main

import (
	"gd_management_gateway/controllers/ctrl_v1"
	_ "gd_management_gateway/routers"
	"gd_management_gateway/rpc_apis"
	"flag"
	"fmt"
	"os"
	"strings"
	gconfig "gd_management_gateway/common.in/config"
	//"gd_management_gateway/common.in/cache"
	"gd_management_gateway/common.in/cache"
	"gd_management_gateway/common.in/clinit"
	"gd_management_gateway/common.in/config"
	"gd_management_gateway/common.in/httper"
	"gd_management_gateway/common.in/logger"
	dsignal "gd_management_gateway/common.in/signal"
	"gd_management_gateway/common.in/task"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	//"github.com/gomodule/redigo/redis"
)

var (
	// 这里要改默认值
	configFile = flag.String("config", "/etc/gd_management_gateway/app.conf", "config file location")
	version    = flag.Bool("version", false, "config file location")
	GitCommit  = "library-import"
	Version    = "library-import"
)

func showVersion() {
	fmt.Println("Version:  ", Version)
	fmt.Println("GitCommit:", GitCommit)
}

func prepare(projectName, runmode, key, logDir string, etcdAddrs []string) {
	discoveryType := beego.AppConfig.String("discovery_type")
	var conf *config.Configure

	// 先行于读配置
	if discoveryType == "k8s" {
		conf = config.GetConfigForK8s()
		if conf == nil {
			fmt.Printf("get conf failed\n\n")
			os.Exit(1)
		}
		rpc_apis.InitForK8s(conf)
		ctrl_v1.PdfFont1File = "mplus-1p-bold.ttf"
		ctrl_v1.PdfFont2File = "microsoft.ttf"
	} else {
		clinit.InitEtcd(etcdAddrs)
		conf = config.GetConfig(projectName+"/"+runmode, key, clinit.GetEtcdClient())
		if conf == nil {
			fmt.Printf("get conf failed\n\n")
			os.Exit(1)
		}
		// 初始化所调用的微服务
		//rpc_apis.Init(etcdAddrs, conf)
		rpc_apis.Init(etcdAddrs, conf)
	}
	appname := conf.Cgi.Gateway.Name
	redisdb := conf.Redis.DefaultDB
	cache.InitRedis(&cache.RedisConfig{
		Addrs:        strings.Split(conf.Redis.Addrs, ","),
		Password:     conf.Redis.Password,
		DB:           redisdb,
		PoolSize:     conf.Redis.PoolSize,
		MinIdleConns: conf.Redis.MinIdleConns,
		MaxRetries:   conf.Redis.MaxRetries,
		IsCluster:    conf.Redis.IsCluster,
	})

	// 初始化logger
	ms, _ := conf.Cgi.Gateway.Log.MaxSize.Int64()
	mb, _ := conf.Cgi.Gateway.Log.MaxBackups.Int64()
	ma, _ := conf.Cgi.Gateway.Log.MaxAge.Int64()
	maxSize := int(ms)
	maxBackups := int(mb)
	maxAge := int(ma)
	disableStacktrace := (conf.Cgi.Gateway.Log.DisableStacktrace == "true")
	// 通用logger
	commonLogger := logger.InitLogger(runmode, fmt.Sprintf("%s/%s.log", logDir, appname),
		maxSize, maxBackups, maxAge, disableStacktrace)
	// 单独设置
	accessLogger := logger.NewInfoLogger(runmode, fmt.Sprintf("%s/%s-access.log", logDir, appname),
		maxSize, maxBackups, maxAge)

	// 设置需要使用logger的地方
	// common日志
	ctrl_v1.SetLogger(commonLogger)
	// access日志
	task.SetLogger(accessLogger)

	// 打开第三方包调试开关
	if runmode != "prod" {
		orm.Debug = true
		//redis.Debug = true
		httper.Debug = true
		httper.DebugLog = commonLogger
	}
}

func main() {
	flag.Parse()

	if *version {
		showVersion()
	}
	if err := beego.LoadAppConfig("ini", *configFile); err != nil {
		fmt.Printf("Fail to read file: %v\n\n", err)
		os.Exit(1)
	}
	runmode := beego.AppConfig.String("runmode")
	//serveAddr := beego.AppConfig.String("serve_addr")
	//appname := beego.AppConfig.String("appname")
	logDir := beego.AppConfig.String("log_dir")
	etcdAddrs := strings.Split(beego.AppConfig.String("etcd_addrs"), ",")
	encryptKey := beego.AppConfig.String("encrypt_key")
	projectName := beego.AppConfig.String("project_name")
	swaggerDir := beego.AppConfig.String("swagger_dir")
	exportDir := beego.AppConfig.String("export_dir")
	apiTaskDir := beego.AppConfig.String("api_task_dir")
	outip := beego.AppConfig.String("outip")
	prepare(projectName, runmode, encryptKey, logDir, etcdAddrs)
	fmt.Printf("swagger:%s\n", swaggerDir)
	if runmode == "dev" || runmode == "test" {
		beego.BConfig.WebConfig.DirectoryIndex = true
		if swaggerDir == "" {
			beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
		} else {
			beego.BConfig.WebConfig.StaticDir["/swagger"] = swaggerDir
		}
	}
	if exportDir == "" {
		beego.BConfig.WebConfig.StaticDir["/export"] = "/mnt/"
	} else {
		if strings.HasSuffix(exportDir, "/") {
			beego.BConfig.WebConfig.StaticDir["/export"] = exportDir
		} else {
			beego.BConfig.WebConfig.StaticDir["/export"] = exportDir + "/"
		}

	}
	if beego.AppConfig.String("discovery_type") == "k8s" {
		ctrl_v1.DiscoveryType = "k8s"
	}
	if apiTaskDir == "" {
		beego.BConfig.WebConfig.StaticDir["/try_api_task_dir"] = "/mnt/try_api_task/"
		os.Mkdir(beego.BConfig.WebConfig.StaticDir["/try_api_task_dir"], 0666)
		os.Chmod(beego.BConfig.WebConfig.StaticDir["/try_api_task_dir"], 0777)

	} else {
		if strings.HasSuffix(apiTaskDir, "/") {
			beego.BConfig.WebConfig.StaticDir["/try_api_task_dir"] = apiTaskDir
		} else {
			beego.BConfig.WebConfig.StaticDir["/try_api_task_dir"] = apiTaskDir + "/"
		}

	}
	serveAddr := fmt.Sprintf("%s:%s",gconfig.Conf.Cgi.Gateway.ServiceName,gconfig.Conf.Cgi.Gateway.ServicePort.String())
	array := strings.Split(serveAddr, ":")
	if len(array) > 1 {
		ctrl_v1.ServerPort = array[1]
		ctrl_v1.ServerIp = outip
	}
	fmt.Printf("!!!!:%v,%v\n", runmode, swaggerDir)
	ctrl_v1.Watch()
	dsignal.HandleExitSignal()
	beego.Run(serveAddr)
}
