from typing import 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._RootEntity import _RootEntity
from common.database.api.entity.EntityCollection import EntityCollection
from common.database.engines._DatabaseEngine import _DatabaseEngine

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

class Context(_RootEntity):
    def __init__(self, context_uuid : str, database_engine : _DatabaseEngine):
        super().__init__(database_engine, context_uuid, KEY_CONTEXT, VALIDATORS, TRANSCODERS)
        self._topologies = EntityCollection(self, KEY_TOPOLOGIES)
        self._services = EntityCollection(self, KEY_SERVICES)

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

    @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': 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.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(),
        }