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

import pymongo
import json
from db.entities.user import User
from typing import List

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

    def __init__(self):
        super().__init__(netconst.REST_GATEWAY_DB_HOSTNAME,
                         netconst.REST_GATEWAY_DB_PORT,
                         'rest-gateway-db')

        self._user_collection = 'user'

    def one_by_username(self, username : str) -> User:
        return list(super().get_entries(self._user_collection, selection={"username": username}))

    def add(self, user : User):
        super().insert_entry(self._user_collection, user.to_serializable_dict())
    
    def update(self, user: User):
        collection = self._database[self._user_collection]
        collection.update_one({"username":user.username}, {"$set": user.to_serializable_dict()})
    
    def delete_all_with_username(self, username: str):
        collection = self._database[self._user_collection]
        collection.delete_many({"username": username})
        # TODO maybe movable to MongoRepositoryBase?

    def all(self) -> List[User]:
        result = super().get_entries(self._user_collection, projection={'_id': False})

        return list(result)