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

import pymongo
import json
from typing import List, Dict

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

    def __init__(self):
        super().__init__(netconst.BUSINESS_LOGIC_DB_HOSTNAME,
                         netconst.BUSINESS_LOGIC_DB_PORT,
                         'rest-gateway-db')

        self._transaction_collection = 'transactions'
    
    def delete_all_transactions(self):
        collection = self._database[self._transaction_collection]
        collection.delete_many({})

    def add_transaction(self, transaction: Transaction):
        reference = self.get_transaction_with_id(transaction.id())
        if reference == None:
            super().insert_entry(self._transaction_collection, transaction.to_serializable_dict())
    
    def all_transactions_for_use_case(self, use_case: str) -> List[Transaction]:
        result = super().get_entries(self._transaction_collection, projection={'_id': False}, selection={"use_case": use_case})
        return [Transaction.from_serializable_dict(row) for row in list(result)]
    
    def get_transaction_with_id(self, unique_id: str) -> Transaction:
        result = list(super().get_entries(self._transaction_collection, projection={'_id': False}, selection={"id": unique_id}))

        if len(result) == 1:
            return Transaction.from_serializable_dict(result[0])
        
        return None