package mdb

import (
	"github.com/go-redis/redis/v8"
	mhayaGORM "github.com/mhaya/components/gorm"
	mhayaMongo "github.com/mhaya/components/mongo"
	"github.com/mhaya/game/game_cluster/internal/mdb/eventmodels"
	clog "github.com/mhaya/logger"
	cactor "github.com/mhaya/net/actor"
	cprofile "github.com/mhaya/profile"
	"go.mongodb.org/mongo-driver/mongo"
	"gorm.io/gorm"
)

type ActorDB struct {
	cactor.Base
}

var (
	LogstashDB *gorm.DB
	MDB        *mongo.Database
	RDB        redis.UniversalClient
)

func (p *ActorDB) AliasID() string {
	return "db"
}

// OnInit Actor初始化前触发该函数
func (p *ActorDB) OnInit() {
	if p.App().Find(mhayaMongo.Name) != nil {
		mongo := p.App().Find(mhayaMongo.Name).(*mhayaMongo.Component)
		if mongo == nil {
			clog.DPanicf("[component = %s] not found.", mhayaMongo.Name)
		}

		// 获取 db_id = "center_db_1" 的配置
		dbID := p.App().Settings().GetConfig("db_id_list").GetString("game_db_id")
		MDB = mongo.GetDb(dbID)
		if MDB == nil {
			clog.Panic("game_db_id not found, dbID:" + dbID)
		}
	}

	if p.App().Find(mhayaGORM.Name) != nil {
		gormComponent := p.App().Find(mhayaGORM.Name).(*mhayaGORM.Component)
		if gormComponent == nil {
			clog.DPanicf("[component = %s] not found.", mhayaGORM.Name)
		}

		// 获取 db_id = "center_db_1" 的配置
		dbID := p.App().Settings().GetConfig("db_id_list").GetString("logstash_db_id")
		LogstashDB = gormComponent.GetDb(dbID)
		if LogstashDB == nil {
			clog.Panic("logstash_db_id not found, dbID:" + dbID)
		}

		LogstashMigrateTables()
	}

	redisConfig := cprofile.GetConfig("redis")
	/*	tlsConfig := &tls.Config{
		MinVersion:               tls.VersionTLS12,
		PreferServerCipherSuites: true,
	}*/
	RDB = redis.NewUniversalClient(&redis.UniversalOptions{
		Addrs:    []string{redisConfig.GetString("address")},
		Password: redisConfig.GetString("password"),
		DB:       redisConfig.GetInt("db"),
		//TLSConfig: tlsConfig,
	})

	if p.App().NodeId() == "m-center" {
		SetIndex()
	}
}

func LogstashMigrateTables() {
	LogstashDB.AutoMigrate(&eventmodels.UserRegisterEventContent{})
	LogstashDB.AutoMigrate(&eventmodels.UserLoginEventContent{})
	LogstashDB.AutoMigrate(&eventmodels.UserUpdateInfoEventContent{})
	LogstashDB.AutoMigrate(&eventmodels.UserWithdrawEventContent{})
	LogstashDB.AutoMigrate(&eventmodels.AssetsEventContent{})
	LogstashDB.AutoMigrate(&eventmodels.InviteEventContent{})
	LogstashDB.AutoMigrate(&eventmodels.DiceEventContent{})
	LogstashDB.AutoMigrate(&eventmodels.TurntableEventContent{})
	LogstashDB.AutoMigrate(&eventmodels.JoinChannelEventContent{})
	LogstashDB.AutoMigrate(&eventmodels.FollowEventContent{})
	LogstashDB.AutoMigrate(&eventmodels.TaskFinishEventContent{})
	LogstashDB.AutoMigrate(&eventmodels.BackendOperationEventContent{})
}
