import logging
from typing import Dict, List, Optional, Tuple
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
from service.proto.context_pb2 import EndPointId
from .DeviceModel import DeviceModel
from .TopologyModel import TopologyModel

LOGGER = logging.getLogger(__name__)

class EndPointModel(Model):
    pk = PrimaryKeyField()
    topology_fk = ForeignKeyField(TopologyModel, required=False)
    device_fk = ForeignKeyField(DeviceModel)
    endpoint_uuid = StringField(required=True, allow_empty=False)
    endpoint_type = StringField()

    def dump_id(self) -> Dict:
        device_id = DeviceModel(self.database, self.device_fk).dump_id()
        result = {
            'device_id': device_id,
            'endpoint_uuid': {'uuid': self.endpoint_uuid},
        }
        if self.topology_fk is not None:
            result['topology_id'] = TopologyModel(self.database, self.topology_fk).dump_id()
        return result

    def dump(self) -> Dict:
        return {
            'endpoint_id': self.dump_id(),
            'endpoint_type': self.endpoint_type,
        }

def grpc_endpointids_to_raw(grpc_endpointids : List[EndPointId]) -> List[Tuple[str, str, Optional[str]]]:
    def translate(grpc_endpointid : EndPointId) -> Tuple[str, str, Optional[str]]:
        device_uuid   = grpc_endpointid.device_id.device_uuid.uuid
        endpoint_uuid = grpc_endpointid.endpoint_uuid.uuid
        topology_uuid = grpc_endpointid.topology_id.topology_uuid.uuid
        if len(topology_uuid) == 0: topology_uuid = None
        return device_uuid, endpoint_uuid, topology_uuid
    return [translate(grpc_endpointid) for grpc_endpointid in grpc_endpointids]
