import logging
from flask.json import jsonify
from flask_restful import Resource
from common.Settings import get_setting
from common.Constants import DEFAULT_CONTEXT_UUID
from service.client.ServiceClient import ServiceClient
from service.proto.context_pb2 import Service, ServiceStatusEnum, ServiceTypeEnum

LOGGER = logging.getLogger(__name__)

class Compute(Resource):
    def __init__(self) -> None:
        super().__init__()

    def get(self):
        # Here implement HTTP GET method
        raise NotImplementedError()

    def post(self):
        # Here implement HTTP POST method

        # Retrieve required data from request
        new_service_context_id = DEFAULT_CONTEXT_UUID
        new_service_id = 'my-service-id'

        # Find Service address/port from environment and instantiate client
        service_host = get_setting('SERVICESERVICE_SERVICE_HOST')
        service_port = get_setting('SERVICESERVICE_SERVICE_PORT_GRPC')
        service_client = ServiceClient(service_host, service_port)

        # Compose a dummy CreateService request
        request = Service()
        request.service_id.context_id.context_uuid.uuid = new_service_context_id
        request.service_id.service_uuid.uuid = new_service_id
        request.service_type = ServiceTypeEnum.SERVICETYPE_L2NM
        request.service_status.service_status = ServiceStatusEnum.SERVICESTATUS_PLANNED
        
        try:
            # Issue gRPC request to Service component
            reply = service_client.CreateService(request)

            # Parse CreateService reply, here we check that obtained service Id and context are the expected ones.
            reply_context_uuid = reply.context_id.context_uuid.uuid
            reply_service_uuid = reply.service_uuid.uuid
            #succeeded = (reply_context_uuid == new_service_context_id) and (reply_service_uuid == new_service_id)
            succeeded = True
            reply = {'succeeded': succeeded}
        except Exception as e:
            LOGGER.exception('Something went wrong Creating Service {:s}'.format(str(request)))
            reply = {'succeeded': False, 'error': str(e)}

        return jsonify(reply)
