# 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 copy, grpc, logging
from typing import Optional
from common.Constants import DEFAULT_CONTEXT_UUID
from common.proto.dlt_gateway_pb2 import DltRecord, DltRecordId, DltRecordOperationEnum, DltRecordTypeEnum
from common.rpc_method_wrapper.Decorator import create_metrics, safe_and_metered_rpc_method
from common.proto.context_pb2 import DeviceId, Empty, ServiceId, SliceId
from common.proto.dlt_connector_pb2_grpc import DltConnectorServiceServicer
from common.tools.grpc.Tools import grpc_message_to_json_string
from context.client.ContextClient import ContextClient
from dlt.connector.client.DltGatewayClient import DltGatewayClient

LOGGER = logging.getLogger(__name__)

SERVICE_NAME = 'DltConnector'
METHOD_NAMES = [
    'RecordAll',
    'RecordAllDevices', 'RecordDevice',
    'RecordAllServices', 'RecordService',
    'RecordAllSlices', 'RecordSlice',
]
METRICS = create_metrics(SERVICE_NAME, METHOD_NAMES)

class DltConnectorServiceServicerImpl(DltConnectorServiceServicer):
    def __init__(self):
        LOGGER.debug('Creating Servicer...')
        self._own_domain_uuid : Optional[str] = None
        LOGGER.debug('Servicer Created')

    @property
    def own_domain_id(self) -> str:
        if self._own_domain_uuid is not None: return self._own_domain_uuid

        context_client = ContextClient()
        existing_context_ids = context_client.ListContextIds(Empty())
        existing_context_uuids = {context_id.context_uuid.uuid for context_id in existing_context_ids.context_ids}

        # Detect local context name (will be used as abstracted device name); exclude DEFAULT_CONTEXT_UUID
        existing_non_admin_context_uuids = copy.deepcopy(existing_context_uuids)
        existing_non_admin_context_uuids.discard(DEFAULT_CONTEXT_UUID)
        if len(existing_non_admin_context_uuids) != 1:
            MSG = 'Unable to identify own domain name. Existing Contexts({:s})'
            raise Exception(MSG.format(str(existing_context_uuids)))
        self._own_domain_uuid = existing_non_admin_context_uuids.pop()
        return self._own_domain_uuid

    @safe_and_metered_rpc_method(METRICS, LOGGER)
    def RecordAll(self, request : Empty, context : grpc.ServicerContext) -> Empty:
        return Empty()

    @safe_and_metered_rpc_method(METRICS, LOGGER)
    def RecordAllDevices(self, request : Empty, context : grpc.ServicerContext) -> Empty:
        return Empty()

    @safe_and_metered_rpc_method(METRICS, LOGGER)
    def RecordDevice(self, request : DeviceId, context : grpc.ServicerContext) -> Empty:
        context_client = ContextClient()
        device = context_client.GetDevice(request)

        dltgateway_client = DltGatewayClient()

        dlt_record_id = DltRecordId()
        dlt_record_id.domain_uuid.uuid = self.own_domain_id
        dlt_record_id.type             = DltRecordTypeEnum.DLTRECORDTYPE_DEVICE
        dlt_record_id.record_uuid.uuid = device.device_id.device_uuid.uuid

        LOGGER.info('[RecordDevice] sent dlt_record_id = {:s}'.format(grpc_message_to_json_string(dlt_record_id)))
        dlt_record = dltgateway_client.GetFromDlt(dlt_record_id)
        LOGGER.info('[RecordDevice] recv dlt_record = {:s}'.format(grpc_message_to_json_string(dlt_record)))

        exists = False

        dlt_record = DltRecord()
        dlt_record.record_id.CopyFrom(dlt_record_id)
        dlt_record.operation = \
            DltRecordOperationEnum.DLTRECORDOPERATION_UPDATE \
            if exists else \
            DltRecordOperationEnum.DLTRECORDOPERATION_ADD

        dlt_record.data_json = grpc_message_to_json_string(device)
        LOGGER.info('[RecordDevice] sent dlt_record = {:s}'.format(grpc_message_to_json_string(dlt_record)))
        dlt_record_status = dltgateway_client.RecordToDlt(dlt_record)
        LOGGER.info('[RecordDevice] recv dlt_record_status = {:s}'.format(grpc_message_to_json_string(dlt_record_status)))
        return Empty()

    @safe_and_metered_rpc_method(METRICS, LOGGER)
    def RecordAllServices(self, request : Empty, context : grpc.ServicerContext) -> Empty:
        return Empty()

    @safe_and_metered_rpc_method(METRICS, LOGGER)
    def RecordService(self, request : ServiceId, context : grpc.ServicerContext) -> Empty:
        return Empty()

    @safe_and_metered_rpc_method(METRICS, LOGGER)
    def RecordAllSlices(self, request : Empty, context : grpc.ServicerContext) -> Empty:
        return Empty()

    @safe_and_metered_rpc_method(METRICS, LOGGER)
    def RecordSlice(self, request : SliceId, context : grpc.ServicerContext) -> Empty:
        return Empty()
