import os
import pymongo
from pymongo import MongoClient
import urllib.parse

class MongoDB:
    def __init__(self, connection_string: str):
        self.client = MongoClient(connection_string)
        self.db = self.client.my_database  # Replace 'my_database' with your actual database name

    def close(self):
        self.client.close()


# MongoDB connection setup
def get_mongo_db():
    mongo_host = os.getenv("MONGO_HOST", "localhost")
    mongo_user = os.getenv("MONGO_USER")  # No default value
    mongo_pass = os.getenv("MONGO_PASS")  # No default value
    mongo_db_name = os.getenv("MONGO_DB")
    mongo_uri = os.getenv("MONGO_URI")

    if not mongo_uri:
        if mongo_user and mongo_pass:
            # Ensure password is URL encoded if it contains special characters
            mongo_pass = urllib.parse.quote_plus(mongo_pass)
            mongo_uri = f"mongodb://{mongo_user}:{mongo_pass}@{mongo_host}:27017/{mongo_db_name}"
        else:
            mongo_uri = f"mongodb://{mongo_host}:27017/movex"

    client = pymongo.MongoClient(mongo_uri)
    db = client[mongo_db_name]
    #print("DB getting connected now")
    try:
        #print("DB connection is OPEN now.....")
        yield db
    finally:
        # Assuming MongoDB instance is available through db.client here
        #print("DB connection is Closed now.....")
        db.client.close()
    return 