# 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, os, pytest, time
from common.tests.MockService import MockService
from common.tests.MockServicerImpl_Context import MockServicerImpl_Context
from common.tests.MockServicerImpl_Service import MockServicerImpl_Service
from common.tests.MockServicerImpl_Slice import MockServicerImpl_Slice
from compute.Config import RESTAPI_SERVICE_PORT, RESTAPI_BASE_URL
from compute.service.rest_server.RestServer import RestServer
from context.proto.context_pb2_grpc import add_ContextServiceServicer_to_server
from service.proto.service_pb2_grpc import add_ServiceServiceServicer_to_server
from slice.proto.slice_pb2_grpc import add_SliceServiceServicer_to_server
from .mock_osm.MockOSM import MockOSM
from .Constants import (
    SERVICE_CONNECTION_POINTS_1, SERVICE_CONNECTION_POINTS_2, SERVICE_TYPE, WIM_MAPPING, WIM_USERNAME, WIM_PASSWORD)

LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)

LOCALHOST = '127.0.0.1'
MOCKSERVER_GRPC_PORT = 10000
COMPUTE_RESTAPI_PORT = 10000 + RESTAPI_SERVICE_PORT # avoid privileged ports

class MockService_ContextService(MockService):
    # Mock Server implementing Context and Service to simplify unitary tests of Compute

    def __init__(self, cls_name='MockService_Service'):
        super().__init__(LOCALHOST, MOCKSERVER_GRPC_PORT, cls_name=cls_name)

    # pylint: disable=attribute-defined-outside-init
    def install_servicers(self):
        self.context_servicer = MockServicerImpl_Context()
        add_ContextServiceServicer_to_server(self.context_servicer, self.server)
        self.service_servicer = MockServicerImpl_Service()
        add_ServiceServiceServicer_to_server(self.service_servicer, self.server)
        self.slice_servicer = MockServicerImpl_Slice()
        add_SliceServiceServicer_to_server(self.slice_servicer, self.server)

os.environ['CONTEXTSERVICE_SERVICE_HOST'] = LOCALHOST
os.environ['CONTEXTSERVICE_SERVICE_PORT_GRPC'] = str(MOCKSERVER_GRPC_PORT)
os.environ['SERVICESERVICE_SERVICE_HOST'] = LOCALHOST
os.environ['SERVICESERVICE_SERVICE_PORT_GRPC'] = str(MOCKSERVER_GRPC_PORT)
os.environ['SLICESERVICE_SERVICE_HOST'] = LOCALHOST
os.environ['SLICESERVICE_SERVICE_PORT_GRPC'] = str(MOCKSERVER_GRPC_PORT)

# NBI Plugin IETF L2VPN requires environment variables CONTEXTSERVICE_SERVICE_HOST, CONTEXTSERVICE_SERVICE_PORT_GRPC,
# SERVICESERVICE_SERVICE_HOST, and SERVICESERVICE_SERVICE_PORT_GRPC to work properly.
# pylint: disable=wrong-import-position,ungrouped-imports
from compute.service.rest_server.nbi_plugins.ietf_l2vpn import register_ietf_l2vpn

@pytest.fixture(scope='session')
def mockservice():
    _service = MockService_ContextService()
    _service.start()
    yield _service
    _service.stop()

@pytest.fixture(scope='session')
def compute_service_rest(mockservice):  # pylint: disable=redefined-outer-name
    _rest_server = RestServer(port=COMPUTE_RESTAPI_PORT, base_url=RESTAPI_BASE_URL)
    register_ietf_l2vpn(_rest_server)
    _rest_server.start()
    time.sleep(1) # bring time for the server to start
    yield _rest_server
    _rest_server.shutdown()
    _rest_server.join()

@pytest.fixture(scope='session')
def osm_wim(compute_service_rest): # pylint: disable=redefined-outer-name
    wim_url = 'http://{:s}:{:d}'.format(LOCALHOST, COMPUTE_RESTAPI_PORT)
    return MockOSM(wim_url, WIM_MAPPING, WIM_USERNAME, WIM_PASSWORD)

def test_compute_create_connectivity_service_rest_api(osm_wim : MockOSM): # pylint: disable=redefined-outer-name
    osm_wim.create_connectivity_service(SERVICE_TYPE, SERVICE_CONNECTION_POINTS_1)

def test_compute_get_connectivity_service_status_rest_api(osm_wim : MockOSM): # pylint: disable=redefined-outer-name
    service_uuid = list(osm_wim.conn_info.keys())[0] # this test adds a single service
    osm_wim.get_connectivity_service_status(service_uuid)

def test_compute_edit_connectivity_service_rest_api(osm_wim : MockOSM): # pylint: disable=redefined-outer-name
    service_uuid = list(osm_wim.conn_info.keys())[0] # this test adds a single service
    osm_wim.edit_connectivity_service(service_uuid, SERVICE_CONNECTION_POINTS_2)

def test_compute_delete_connectivity_service_rest_api(osm_wim : MockOSM): # pylint: disable=redefined-outer-name
    service_uuid = list(osm_wim.conn_info.keys())[0] # this test adds a single service
    osm_wim.delete_connectivity_service(service_uuid)
