from __future__ import annotations
from typing import TYPE_CHECKING, Dict
from ..entity._Entity import _Entity
from ..entity.EntityAttributes import EntityAttributes
from ..entity.EntityCollection import EntityCollection
from .Keys import KEY_TOPOLOGY, KEY_DEVICES, KEY_LINKS
from .Device import Device
from .Link import Link

if TYPE_CHECKING:
    from .Context import Context

VALIDATORS = {}

class Topology(_Entity):
    def __init__(self, topology_uuid : str, parent : 'Context'):
        super().__init__(parent=parent)
        self._topology_uuid = topology_uuid
        self._context_uuid = self._parent.context_uuid
        self._attributes = EntityAttributes(self, KEY_TOPOLOGY, validators=VALIDATORS)
        self._devices = EntityCollection(self, KEY_DEVICES)
        self._links = EntityCollection(self, KEY_LINKS)

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

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

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

    @property
    def topology_uuid(self) -> str: return self._topology_uuid

    @property
    def attributes(self) -> EntityAttributes: return self._attributes

    @property
    def devices(self) -> EntityCollection: return self._devices

    def device(self, device_uuid : str) -> Device: return Device(device_uuid, self)

    @property
    def links(self) -> EntityCollection: return self._links

    def link(self, link_uuid : str) -> Link: return Link(link_uuid, self)

    def create(self) -> 'Topology':
        self.parent.topologies.add(self.topology_uuid)
        return self

    def delete(self):
        for device_uuid in self.devices.get(): self.device(device_uuid).delete()
        for link_uuid in self.links.get(): self.link(link_uuid).delete()
        self.attributes.delete()
        self.parent.topologies.delete(self.topology_uuid)

    def dump(self) -> Dict:
        devices = [self.device(device_uuid).dump() for device_uuid in self.devices.get()]
        links   = [self.link  (link_uuid  ).dump() for link_uuid   in self.links.get()]
        return {
            'topoId': {
                'contextId': {'contextUuid': {'uuid': self.context_uuid}},
                'topoId': {'uuid': self.topology_uuid},
            },
            'device': devices,
            'link': links,
        }
