package global

import (
	"encoding/json"
	"github.com/Shopify/sarama"
	"github.com/valyala/fasthttp"
	"github.com/vrg0/go-common/args"
	"github.com/vrg0/go-common/conf"
	"github.com/vrg0/go-common/kafka"
	"github.com/vrg0/go-common/logger"
	"github.com/vrg0/go-common/util"
	"go.uber.org/zap/zapcore"
	"os"
	"strings"
)

const (
	AppName = "enoch"

	//NAMESPACE
	NamespaceApplication = "application"
	NamespaceTechDeploy  = "tech.deploy"
	NamespaceTechSleuth  = "tech.sleuth"

	//kafka group
	KafkaGroup = AppName

	//influxDB的数据库名称
	InfluxDbName = "monitor"

	BatchSize = 4096
)

var (
	Env                            = args.GetOrDefault("env", "dev")
	Idc                            = args.GetOrDefault("idc", "k8s")
	EosNamespace                   = args.GetOrDefault("eos_namespace", "arch")
	EosHost                        = args.GetOrDefault("eos_host", "http://eos.quantgroups.com/")
	LocalIp, _                     = util.LocalIp()
	Config          *conf.Conf     = nil
	Logger          *logger.Logger = nil
	KafkaVersion                   = sarama.V1_0_0_0
	KafkaRecver     *kafka.Recver  = nil
	InfluxDbAddress                = ""
	DaoFileCacheDir                = ""
)

type EosResult struct {
	Success bool                   `json:"success"`
	Details map[string]interface{} `json:"details"`
}

func init() {
	//初始化配置
	url := "apollo-" + Env + ".quantgroups.com/"
	if config, err := conf.New(url, AppName, Idc, os.Args[0]+".cache_file", nil); err != nil {
		panic(err)
	} else {
		Config = config
	}

	//测试环境添加kv替换
	if IsDev() {
		statusCode, body, err := fasthttp.Get(nil, EosHost+"api/apollo/env_vars?namespace="+EosNamespace)
		if err != nil {
			panic(err)
		}
		if statusCode != 200 {
			panic("初始化eos数据出错:" + string(body))
		}
		var result = EosResult{}
		err = json.Unmarshal(body, &result)
		if !result.Success {
			panic("eos数据解析出错" + string(body))
		}
		kvMap := make(map[string]string)
		for k, v := range result.Details {
			if _, ok := v.(string); ok {
				kvMap[k] = v.(string)
			}
		}
		Config.RefreshKvMap(kvMap)
	}

	//初始化日志
	logPath := Config.GetOrDefault(NamespaceApplication, "log.dir", "/dev/stdout")
	logLevel := getLoggerLevel(Config.GetOrDefault(NamespaceApplication, "log.level", "info"))
	Logger = logger.New(logPath, logLevel)

	//初始化kafka
	kafkaLogger := Logger.GetStandardLogger()
	kafkaLogger.SetPrefix("_KAFKA_RECVER_ ")

	kafkaAddress, ok := Config.Get(NamespaceTechSleuth, "tech.enoch.kafkaHost")
	if !ok {
		Logger.Fatal("can not get kafka address")
	} else {
		Logger.Info("kafkaAddress:", kafkaAddress)
	}
	KafkaRecver = kafka.NewRecver(KafkaVersion, strings.Split(kafkaAddress, ","), kafkaLogger)

	InfluxDbAddress = Config.GetOrDefault(NamespaceApplication, "influxdb.address", "")
	DaoFileCacheDir = Config.GetOrDefault(NamespaceApplication, "dao.file.cache.dir", "/var")
}

func getLoggerLevel(level string) zapcore.Level {
	switch strings.ToLower(level) {
	case "info":
		return zapcore.InfoLevel
	case "debug":
		return zapcore.DebugLevel
	case "panic":
		return zapcore.PanicLevel
	case "warning":
		return zapcore.WarnLevel
	case "fatal":
		return zapcore.FatalLevel
	case "error":
		return zapcore.ErrorLevel
	default:
		return zapcore.InfoLevel
	}
}

func IsDev() bool {
	return strings.ToUpper(Env) == "DEV"
}
