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

from typing import Dict, List

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

        self._collection = 'tables'
    
    def get_all(self) -> List[Table]:
        result = super().get_entries(self._collection, projection={'_id': False})
        return [Table.from_serializable_dict(row) for row in list(result)]
    
    def get_all_for_use_case(self, use_case:str) -> List[Table]:
        result = super().get_entries(self._collection, selection={'use_case': use_case}, projection={'_id': False})
        return [Table.from_serializable_dict(row) for row in result]
    
    def get_for_use_case_and_name(self, use_case:str, name:str) -> Table:
        result = list(super().get_entries(self._collection, selection={"use_case":use_case, "name":name}, projection={'_id': False}))

        if len(result) == 1:
            return Table.from_serializable_dict(result[0])
        if len(result) == 0:
            return None
        
        raise ValueError("No more than 1 Schema allowed per use-case!")

    def add(self, table:Table):
        super().insert_entry(self._collection, table.to_serializable_dict())

    def delete_for_use_case(self, use_case: str): 
        collection = self._database[self._collection]
        collection.delete_many({"use_case": use_case})
    
    def delete_all(self):
        collection = self._database[self._collection]
        collection.delete_many({})
    
    def update(self, table: Table):
        collection = self._database[self._collection]
        collection.update_one({"use_case": table.use_case, "name": table.name}, {"$set": table.to_serializable_dict()})