import pymongo
import network_constants as netconst

class MongoRepositoryBase:
    '''Base class to connect to, insert and read from a single MongoDB collection'''
    # TODO extract to docker env var
    _username = 'root'
    _password = 'root'

    _collection: pymongo.collection.Collection = None
    _mongo_client: pymongo.MongoClient = None

    def __init__(self,  database_name, collection_name, username=_username, password=_password):
        self._mongo_client = pymongo.MongoClient(f"mongodb://{username}:{password}@{netconst.MONGO_DB_HOSTNAME}:{netconst.MONGO_DB_PORT}/")
        database = self._mongo_client[database_name]
        self._collection = database[collection_name]

    def insert_entry(self, content: dict):
        self._collection.insert_one(content)

    def get_entries(self, selection: dict = {}, projection: dict = {'_': 0}) -> pymongo.cursor.Cursor:
        return self._collection.find(selection, projection)

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