# global imports (dont't worry, red is normal)
import network_constants as netconst
from database.MongoRepositoryBase import MongoRepositoryBase
from db.entities.use_case import UseCase

import pymongo
import json
from typing import List, Dict

class UseCaseRepository(MongoRepositoryBase):
    '''This is a repository for MongoDb.'''

    def __init__(self):
        super().__init__(netconst.BUSINESS_LOGIC_DB_HOSTNAME,
                         netconst.BUSINESS_LOGIC_DB_PORT,
                         'business-logic-db')

        self._use_case_collection = 'use_cases'
    
    def all(self) -> List[UseCase]:
        dicts = list(super().get_entries(self._use_case_collection, projection={'_id': False}))

        return [UseCase.from_serializable_dict(d) for d in dicts]
    
    def delete_all(self):
        collection = self._database[self._use_case_collection]
        collection.delete_many({})
    
    def delete_all_with_name(self, name: str):
        collection = self._database[self._use_case_collection]
        collection.delete_many({"name": name})

    def get_by_name(self, name: str):
        result = list(super().get_entries(self._use_case_collection, {"name":name}))

        if len(result) == 1:
            return UseCase.from_serializable_dict(result[0])
        
        if len(result) == 0:
            return None
        
        raise ValueError("More than one Use-Case in the DB!")

    def put(self, use_case_name: str):
        use_cases = self.all()

        existing_use_cases = list(filter(lambda use_case: use_case.name == use_case_name, use_cases))

        if len(existing_use_cases) == 0:
            use_case = UseCase(use_case_name)
            super().insert_entry(self._use_case_collection, use_case.to_serializable_dict())