from typing import TYPE_CHECKING, Dict, List
from common.database.api.context.service.Service import Service
from common.database.api.context.topology.Topology import Topology
from common.database.api.context.Keys import KEY_CONTEXT, KEY_SERVICES, KEY_TOPOLOGIES
from common.database.api.entity._Entity import _Entity
from common.database.api.entity.EntityCollection import EntityCollection

if TYPE_CHECKING:
    from common.database.api.Database import Database

VALIDATORS = {}  # no attributes accepted
TRANSCODERS = {} # no transcoding applied to attributes

class Context(_Entity):
    def __init__(self, context_uuid : str, parent : 'Database'):
        super().__init__(parent, context_uuid, KEY_CONTEXT, VALIDATORS, TRANSCODERS)
        self._topologies = EntityCollection(self, KEY_TOPOLOGIES)
        self._services = EntityCollection(self, KEY_SERVICES)

    @property
    def parent(self) -> 'Database': return self._parent

    @property
    def context(self) -> 'Context': return self

    @property
    def context_uuid(self) -> str: return self._entity_uuid

    @property
    def topologies(self) -> EntityCollection: return self._topologies

    @property
    def services(self) -> EntityCollection: return self._services

    def topology(self, topology_uuid : str) -> Topology: return Topology(topology_uuid, self)

    def service(self, service_uuid : str) -> Service: return Service(service_uuid, self)

    def create(self) -> 'Context':
        self.parent.contexts.add(self.context_uuid)
        return self

    def delete(self):
        for service_uuid in self.services.get(): self.service(service_uuid).delete()
        for topology_uuid in self.topologies.get(): self.topology(topology_uuid).delete()
        self.parent.contexts.delete(self.context_uuid)
        self.attributes.delete()

    def dump_id(self) -> Dict:
        return {
            'contextUuid': {'uuid': self.context_uuid},
        }

    def dump_topologies(self) -> List:
        return [
            self.topology(topology_uuid).dump() for topology_uuid in self.topologies.get()
        ]

    def dump_services(self) -> List:
        return [
            self.service(service_uuid).dump() for service_uuid in self.services.get()
        ]

    def dump(self) -> Dict:
        return {
            'contextId': self.dump_id(),
            'topologies': self.dump_topologies(),
            'services': self.dump_services(),
        }
