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 MongoClient *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
}

func NewMongoDB(bus *comm.NatsBus) *MongoDB {
	inst, err := bus.NewMongoDBFromConfig("box-mongo")
	if err != nil {
		panic(err)
	}

	MongoClient = &MongoDB{Client: inst.Client, Database: inst.Database, Databases: map[string]*mongo.Database{}}
	return MongoClient
}
