import time

from conio_domain.wallet import WalletCryptoCurrency
from vault_client.client.conio_user import ConioUser

from conio_sdk.generated_protobuf import v1_pb2
from conio_sdk.logging.factory import LOGGING_FACTORY
from conio_sdk.services.conio.trading.trading_service import TradingService
from conio_sdk.services.conio.wallet.bitcoin_wallet_service import BitcoinWalletService


class WalletInfoVOServices:
    _FAKE_WALLET_INFO = v1_pb2.WalletInfo(unconfirmed_satoshi_amount=0, confirmed_satoshi_amount=0)
    _FAKE_CURRENT_BTC_ADDRESS = v1_pb2.CurrentBtcAddress(btc_address_id='')

    def __init__(
            self, bitcoin_wallet_service: BitcoinWalletService,
            trading_service: TradingService):
        self._bitcoin_wallet_service = bitcoin_wallet_service
        self._trading_service = trading_service

    def get_wallet_info(self, user: ConioUser) -> v1_pb2.WalletInfo:
        wallet = user.get_wallet(WalletCryptoCurrency.BITCOIN)
        if not wallet:
            LOGGING_FACTORY.wallet.error('Could not find BTC wallet for user %s', user.reference_key_id)
            return self._FAKE_WALLET_INFO
        # noinspection PyProtectedMember
        response = v1_pb2.WalletInfo(
            **self._bitcoin_wallet_service.get_wallet_balance(wallet['reference_id'])._asdict(),
            timestamp=int(time.time() * 1000)
        )
        response.confirmed_satoshi_amount += sum(
            map(
                lambda d: d.satoshi,
                self._trading_service.get_paid_bids(user)
            )
        )
        return response

    def get_current_btc_address(self, user: ConioUser) -> v1_pb2.CurrentBtcAddress:
        wallet = user.get_wallet(WalletCryptoCurrency.BITCOIN)
        if not wallet:
            LOGGING_FACTORY.wallet.error('Could not find BTC wallet for user %s', user.reference_key_id)
            return self._FAKE_CURRENT_BTC_ADDRESS
        return v1_pb2.CurrentBtcAddress(
            btc_address_id=self._bitcoin_wallet_service.get_current_btc_address(wallet['reference_id'])
        )
