import logging, operator
from typing import Dict, List
from common.orm.fields.ForeignKeyField import ForeignKeyField
from common.orm.fields.PrimaryKeyField import PrimaryKeyField
from common.orm.fields.StringField import StringField
from common.orm.model.Model import Model, get_related_instances
from .ContextModel import ContextModel

LOGGER = logging.getLogger(__name__)

class TopologyModel(Model):
    pk = PrimaryKeyField()
    context_fk = ForeignKeyField(ContextModel)
    topology_uuid = StringField(required=True, allow_empty=False)

    def dump_id(self) -> Dict:
        context_id = ContextModel(self.database, self.context_fk).dump_id()
        return {
            'context_id': context_id,
            'topology_uuid': {'uuid': self.topology_uuid},
        }

    def dump_device_ids(self) -> List[Dict]:
        from .RelationModels import TopologyDeviceModel
        db_devices = get_related_instances(self, TopologyDeviceModel, 'device_fk')
        return [db_device.dump_id() for db_device in sorted(db_devices, key=operator.attrgetter('pk'))]

    def dump_link_ids(self) -> List[Dict]:
        from .RelationModels import TopologyLinkModel
        db_links = get_related_instances(self, TopologyLinkModel, 'link_fk')
        return [db_link.dump_id() for db_link in sorted(db_links, key=operator.attrgetter('pk'))]

    def dump(   # pylint: disable=arguments-differ
            self, include_devices=True, include_links=True
        ) -> Dict:
        result = {'topology_id': self.dump_id()}
        if include_devices: result['device_ids'] = self.dump_device_ids()
        if include_links: result['link_ids'] = self.dump_link_ids()
        return result
