#  Quapp Platform Project
#  qibo_invocation.py
#  Copyright © CITYNOW Co. Ltd. All rights reserved.

from quapp_common.component.backend.invocation import Invocation
from quapp_common.data.request.invocation_request import InvocationRequest
from quapp_common.model.provider.provider import Provider
from ...factory.qibo_device_factory import QiboDeviceFactory
from ...factory.qibo_provider_factory import QiboProviderFactory


class QiboInvocation(Invocation):

    def __init__(self, request_data: InvocationRequest):
        super().__init__(request_data)

    def _export_circuit(self, circuit):
        return None

    def _create_provider(self):
        try:
            self.logger.debug(
                    f'Creating provider: provider_tag={getattr(self.backend_information, "provider_tag", None)}, sdk={getattr(self, "sdk", None)}')
            provider = QiboProviderFactory.create_provider(
                    provider_type=self.backend_information.provider_tag,
                    sdk=self.sdk,
                    authentication=self.backend_information.authentication, )
            self.logger.info(
                    f'Provider created successfully: {type(provider).__name__}')
            return provider
        except Exception as exception:
            self.logger.exception(f'Provider creation failed: {exception}')
            raise

    def _create_device(self, provider: Provider):
        self.logger.debug('Creating device')
        try:
            device_spec = getattr(self.backend_information, "device_name", None)
            self.logger.debug(
                    f'Creating device from provider={type(provider).__name__}, '
                    f'device_specification={device_spec}, sdk={getattr(self, "sdk", None)}', )
            device = QiboDeviceFactory.create_device(provider=provider,
                                                       device_specification=device_spec,
                                                       authentication=self.backend_information.authentication,
                                                       sdk=self.sdk)
            self.logger.info(
                    f'Device created successfully: {type(device).__name__}')
            return device
        except Exception as exception:
            self.logger.exception(f"Device creation failed: {exception}")
            raise

    def _get_qubit_amount(self, circuit):
        return circuit.nqubits