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")

    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/cxnew"

    client = pymongo.MongoClient(mongo_uri)
    return client["cxnew"]

# MongoDB connection setup
def get_mongo_db_old():
    mongo_host = os.getenv("MONGO_HOST", "localhost")
    
    mongo_uri = f"mongodb://{mongo_host}:27017/cxnew"
    client = pymongo.MongoClient(mongo_uri)
    return client["cxnew"]

# Add other database-related functions here
