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

LOGGER = logging.getLogger(__name__)

class LinkModel(Model):
    pk = PrimaryKeyField()
    link_uuid = StringField(required=True, allow_empty=False)

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

    def dump_endpoint_ids(self) -> List[Dict]:
        from .RelationModels import LinkEndPointModel # pylint: disable=import-outside-toplevel
        db_endpoints = get_related_instances(self, LinkEndPointModel, 'endpoint_fk')
        return [db_endpoint.dump_id() for db_endpoint in sorted(db_endpoints, key=operator.attrgetter('pk'))]

    def dump(self) -> Dict:
        return {
            'link_id': self.dump_id(),
            'link_endpoint_ids': self.dump_endpoint_ids(),
        }
