package comm

import (
	"context"
	"errors"
	"fmt"
	"os"
	"strings"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

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

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

func createMongo(mongodns string) (*MongoDB, error) {
	start := strings.LastIndex(mongodns, "/")
	end := strings.LastIndex(mongodns, "?")
	database := mongodns[start+1 : end]
	fmt.Println("mongo-format database => ", database)
	if len(database) < 1 {
		return nil, errors.New("config is not format of mongodb://root:root@172.17.0.1:37017/comm?authSource=admin")
	}
	clientOptions := options.Client().ApplyURI(mongodns)
	// 连接到MongoDB
	mgoCli, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		panic(err)
	}

	// 检查连接
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		panic(err)
	}
	return &MongoDB{Client: mgoCli, Database: mgoCli.Database(database)}, nil
}

func (bus *NatsBus) NewMongoDBFromConfig(mongoConfKey string, timeout ...interface{}) (*MongoDB, error) {
	//mongodb://root:root@172.17.0.1:37017/comm?authSource=admin
	mongodns, err := bus.RequestConfig(mongoConfKey)
	if err != nil {
		return nil, err
	}

	mongoenv := os.Getenv("MONGO")
	if len(mongoenv) > 0 {
		mongodns = mongoenv
	}
	fmt.Println("config mongodns => ", mongodns)
	fmt.Println("env mongodns => ", mongodns)

	return createMongo(mongodns)
}

func (bus *NatsBus) NewMongoDBFromConfigDev(mongoConfKey string, timeout ...interface{}) (*MongoDB, error) {
	//mongodb://root:root@172.17.0.1:37017/comm?authSource=admin
	mongodns, err := bus.RequestConfigDev(mongoConfKey)
	if err != nil {
		return nil, err
	}
	mongoenv := os.Getenv("MONGO")
	if len(mongoenv) > 0 {
		mongodns = mongoenv
	}
	fmt.Println("config mongodns => ", mongodns)
	fmt.Println("env mongodns => ", mongodns)
	return createMongo(mongodns)
}
