from chatter_client.client.service import ChatterMessageService
from conio_sdk_generated.openapi.v2.serde.models.create_wallet import CreateWallet
from vault_client.client.conio_user import ConioUser
from vault_client.generated_protobuf.vault_pb2 import WalletCryptoCurrency

from conio_sdk.common import exceptions
from conio_sdk.services.conio.user.user_service import AuthenticationData, UserService
from conio_sdk.services.conio.wallet.bitcoin_wallet_service import BitcoinWalletService


class CreateWalletVOService:
    _DEFAULT_CRYPTO_CURRENCY = WalletCryptoCurrency.BITCOIN

    def __init__(
            self, wallet_service: BitcoinWalletService,
            user_service: UserService,
            push_notification_service: ChatterMessageService):
        self._wallet_service = wallet_service
        self._user_service = user_service
        self._push_notification_service = push_notification_service

    def create_wallet(
            self, msg: CreateWallet, user: ConioUser,
            access_token: str, hw_id: str) -> AuthenticationData:
        wallet = user.get_wallet(self._DEFAULT_CRYPTO_CURRENCY)
        wallet_reference_id = wallet and wallet.get('reference_id')
        if wallet_reference_id and self._wallet_service.wallet_has_addresses(wallet_reference_id):
            raise exceptions.DuplicateWalletException

        wallet_reference_id = self._wallet_service.create_wallet(user, msg.encrypted_user_key)

        self._push_notification_service.fcm_create_or_update_channel(
            user_info_reference_id=user.reference_key_id,
            wallet_reference_id=wallet_reference_id
        )
        return self._user_service.escalate_token(access_token, hw_id)
