# 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, socket
from common.Constants import DEFAULT_CONTEXT_UUID
from common.Settings import get_setting
from interdomain.Config import GRPC_SERVICE_PORT
from interdomain.client.InterdomainClient import InterdomainClient
from interdomain.proto.context_pb2 import TeraFlowController

LOGGER = logging.getLogger(__name__)

class RemoteDomainClients:
    def __init__(self) -> None:
        self.peer_domain = {}

    def add_peer(
            self, domain_name : str, host : str, port : int, context_uuid : str = DEFAULT_CONTEXT_UUID
        ) -> None:
        while True:
            try:
                remote_teraflow_ip = socket.gethostbyname(host)
                if len(remote_teraflow_ip) > 0: break
            except socket.gaierror as e:
                if str(e) == '[Errno -2] Name or service not known': continue

        interdomain_client = InterdomainClient(host=host, port=port)
        request = TeraFlowController()
        request.context_id.context_uuid.uuid = DEFAULT_CONTEXT_UUID # pylint: disable=no-member
        request.ip_address = get_setting('INTERDOMAINSERVICE_SERVICE_HOST', default='0.0.0.0')
        request.port = int(get_setting('INTERDOMAINSERVICE_SERVICE_PORT_GRPC', default=GRPC_SERVICE_PORT))

        reply = interdomain_client.Authenticate(request)
        if not reply.authenticated:
            msg = 'Authentication against {:s}:{:d} rejected'
            raise Exception(msg.format(str(remote_teraflow_ip), GRPC_SERVICE_PORT))

        self.peer_domain[domain_name] = interdomain_client

    def get_peer(self, domain_name : str) -> InterdomainClient:
        LOGGER.warning('peers: {:s}'.format(str(self.peer_domain)))
        return self.peer_domain.get(domain_name)

    def remove_peer(self, domain_name : str) -> None:
        return self.peer_domain.pop(domain_name, None)
