from flask import session, redirect, url_for, request, Blueprint
from app import config
from app.library.cache import cache
from app.library.crypto import wow_wallet, xmr_wallet
from app.library.crypto import wownero, monero


bp = Blueprint('api', 'api')

@bp.route('/api/prices')
def get_prices():
    prices = {
        'wownero': cache.get_coin_price('wownero')['wownero_price'],
        'monero': cache.get_coin_price('monero')['monero_price'],
    }
    return prices

# todo - do not expose publicly
@bp.route('/api/wallets')
def test():
    wb = wow_wallet.balances()
    d = {
        'wow': {
            'height': wow_wallet.height()['height'],
            'address': wow_wallet.addresses()[0],
        },
        'xmr': {
            'height': xmr_wallet.height()['height'],
            'address': xmr_wallet.addresses()[0],
        }
    }
    return d

@bp.route('/api/convert')
def convert():
    try:
        wow_amount = float(request.args.get('wow', 0.0))
        xmr_amount = float(request.args.get('xmr', 0.0))
        currency = request.args.get('currency', 'usd')
        if wow_amount < 0:
            wow_amount = 0
        if xmr_amount < 0:
            xmr_amount = 0
        return perform_conversion(wow_amount, xmr_amount, currency)
    except:
        return {'error': True}

def perform_conversion(wow_amount, xmr_amount, currency='usd'):
    prices = get_prices()
    fee_percent_int = config.SWAP_FEE_PERCENT
    fee_percent = fee_percent_int / 100
    wow_price = prices['wownero'][currency]
    xmr_price = prices['monero'][currency]
    wow_worth = wow_amount * wow_price
    xmr_worth = xmr_amount * xmr_price
    wow_as_xmr = wow_worth / xmr_price
    xmr_as_wow = xmr_worth / wow_price
    wow_to_xmr_fee_as_usd = fee_percent * wow_worth
    wow_to_xmr_fee_as_xmr = wow_to_xmr_fee_as_usd / xmr_price
    xmr_to_wow_fee_as_usd = fee_percent * xmr_worth
    xmr_to_wow_fee_as_wow = xmr_to_wow_fee_as_usd / wow_price
    res = {
        'wow_amount': wownero.as_real(wow_amount),
        'xmr_amount': monero.as_real(xmr_amount),
        'currency': currency,
        'wow_price': wow_price,
        'xmr_price': xmr_price,
        'wow_worth': round(wow_worth, 4),
        'xmr_worth': round(xmr_worth, 4),
        'wow_as_xmr': monero.as_real(wow_as_xmr),
        'xmr_as_wow': wownero.as_real(xmr_as_wow),
        'wow_to_xmr_fee_as_usd': wow_to_xmr_fee_as_usd,
        'xmr_to_wow_fee_as_usd': xmr_to_wow_fee_as_usd,
        'wow_to_xmr_fee_as_xmr': wow_to_xmr_fee_as_xmr,
        'xmr_to_wow_fee_as_wow': xmr_to_wow_fee_as_wow,
    }
    return res
