package db

import (
	"go.mongodb.org/mongo-driver/mongo"
	"infish.cn/comm"
)

type MongoDB struct {
	Client   *mongo.Client
	Database *mongo.Database

	Databases map[string]*mongo.Database //所有数据库
}

var GMongoDb *MongoDB

func (db *MongoDB) GetCollection(name string) *mongo.Collection {
	return db.Database.Collection(name)
}

func (db *MongoDB) GetDbCollection(dbname string, name string) *mongo.Collection {
	if len(dbname) < 1 {
		return db.GetCollection(name)
	}
	return db.GetOrCreateDatabase(dbname).Collection(name)
}

func (db *MongoDB) GetOrCreateDatabase(name string) *mongo.Database {
	datab := db.Databases[name]
	if datab == nil {
		datab = db.Client.Database(name)
		db.Databases[name] = datab
	}
	return datab
}

var MongoInst *MongoDB = nil

// 从config-service中获取配置，创建
func NewConfigMongoDB(bus *comm.NatsBus) *MongoDB {

	MongoInst, err := bus.NewMongoDBFromConfigDev("mongo")
	if err != nil {
		panic(err)
	}
	GMongoDb = &MongoDB{Client: MongoInst.Client, Database: MongoInst.Database}

	return GMongoDb
}
