import logging, os, pytest, time
from compute.Config import RESTAPI_SERVICE_PORT, RESTAPI_BASE_URL
from compute.service.rest_server.Server import Server
from compute.service.rest_server.resources.Compute import Compute
from service.Config import (
    GRPC_SERVICE_PORT as SERVICE_GRPC_SERVICE_PORT, GRPC_MAX_WORKERS as SERVICE_GRPC_MAX_WORKERS,
    GRPC_GRACE_PERIOD as SERVICE_GRPC_GRACE_PERIOD)
from .mock_osm.MockOSM import MockOSM
from .MockServiceService import MockServiceService

compute_restapi_port = 10000 + RESTAPI_SERVICE_PORT # avoid privileged ports
service_grpc_port = 10000 + SERVICE_GRPC_SERVICE_PORT # avoid privileged ports

os.environ['SERVICESERVICE_SERVICE_HOST'] = '127.0.0.1'
os.environ['SERVICESERVICE_SERVICE_PORT_GRPC'] = str(service_grpc_port)

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

@pytest.fixture(scope='session')
def service_service():
    _service = MockServiceService(
        port=service_grpc_port, max_workers=SERVICE_GRPC_MAX_WORKERS, grace_period=SERVICE_GRPC_GRACE_PERIOD)
    _service.start()
    yield _service
    _service.stop()

@pytest.fixture(scope='session')
def compute_service_rest(service_service):
    _rest_server = Server(port=compute_restapi_port, base_url=RESTAPI_BASE_URL)
    _rest_server.add_resource(Compute, '/vpn-services', endpoint='l2vpn.vpn-services')
    _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(service_service, compute_service_rest): # pylint: disable=redefined-outer-name
    wim_url = 'http://127.0.0.1:{:d}'.format(compute_restapi_port)
    return MockOSM(wim_url)

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

def test_compute_get_connectivity_service_status_rest_api(osm_wim : MockOSM): # pylint: disable=redefined-outer-name
    osm_wim.get_connectivity_service_status()

def test_compute_edit_connectivity_service_rest_api(osm_wim : MockOSM): # pylint: disable=redefined-outer-name
    osm_wim.edit_connectivity_service()

def test_compute_delete_connectivity_service_rest_api(osm_wim : MockOSM): # pylint: disable=redefined-outer-name
    osm_wim.delete_connectivity_service()
