# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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]
