from pymongo import MongoClient, cursor
import network_constants as netconst

class MongoRepositoryBase:
    '''Base class to connect to a MongoDB database'''
    
    # TODO extract to docker env var
    _username = 'root'
    _password = 'root'

    def __init__(self, hostname, port, database_name, username=_username, password=_password):
        self._mongo_client = MongoClient(f"mongodb://{username}:{password}@{hostname}:{port}/")
        self._database = self._mongo_client[database_name]

    def insert_entry(self, collection_name, content: dict):
        collection = self._database[collection_name]
        collection.insert_one(content)

    def get_entries(self, collection_name, selection: dict = {}, projection: dict = {'_': 0}) -> cursor.Cursor:
        collection = self._database[collection_name]
        return collection.find(selection, projection)

    def close_connection(self):
        self._mongo_client.close()
        self._mongo_client = None

