from __future__ import annotations
from typing import TYPE_CHECKING, Dict
from common.database.api.entity._Entity import _Entity
from common.database.api.entity.EntityCollection import EntityCollection
from common.database.api.context.topology.link.Endpoint import Endpoint
from common.database.api.context.Keys import KEY_LINK, KEY_LINK_ENDPOINTS

if TYPE_CHECKING:
    from common.database.api.context.Context import Context
    from common.database.api.context.topology.Topology import Topology

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

class Link(_Entity):
    def __init__(self, link_uuid : str, parent : 'Topology'):
        super().__init__(parent, link_uuid, KEY_LINK, VALIDATORS, TRANSCODERS)
        self._endpoints = EntityCollection(self, KEY_LINK_ENDPOINTS)

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

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

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

    @property
    def topology(self) -> 'Topology': return self.parent

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

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

    @property
    def endpoints(self) -> EntityCollection: return self._endpoints

    def endpoint(self, link_endpoint_uuid : str) -> Endpoint: return Endpoint(link_endpoint_uuid, self)

    def create(self) -> 'Link':
        self.parent.links.add(self.link_uuid)
        return self

    def delete(self) -> None:
        for endpoint_uuid in self.endpoints.get(): self.endpoint(endpoint_uuid).delete()
        self.attributes.delete()
        self.parent.links.delete(self.link_uuid)

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

    def dump(self) -> Dict:
        endpoints = [self.endpoint(link_endpoint_uuid).dump() for link_endpoint_uuid in self.endpoints.get()]
        return {
            'link_id': self.dump_id(),
            'endpointList': endpoints
        }
