import arrow
from statistics import mean
from flask import redirect, url_for, request, Blueprint, render_template
from sqlalchemy import func
from app.models import Swap
from app.routes.api import get_prices, perform_conversion
from app.library.crypto import monero, wownero, wow_wallet, xmr_wallet
from app import config


bp = Blueprint('meta', 'meta')

@bp.route('/')
def index():
    return render_template('index.html')

@bp.route('/stats')
def stats():
    total_earnings = get_total_earnings()
    broken_down_earnings = get_broken_down_earnings()
    stats = get_swap_stats()
    token = config.STATS_TOKEN == request.args.get('token')
    swaps = Swap.query.all()
    if not request.args.get('all'):
        swaps = [s for s in swaps if s.hours_elapsed() < 120]
    return render_template(
        'stats.html',
        wow_balances=wow_wallet.balances(),
        xmr_balances=xmr_wallet.balances(),
        earnings=total_earnings,
        breakdown=broken_down_earnings,
        stats=stats,
        token=token,
        swaps=swaps
    )

def get_swap_stats():
    details = {
        'completed': Swap.query.filter(Swap.completed == True).count(),
        'pending': Swap.query.filter(Swap.completed == False, Swap.funds_received == False).count(),
        'total': Swap.query.count(),
        'in_progress': Swap.query.filter(Swap.completed == False, Swap.funds_received == True).count(),
        'wow_to_xmr': Swap.query.filter(Swap.wow_to_xmr == True).count(),
        'xmr_to_wow': Swap.query.filter(Swap.wow_to_xmr == False).count(),
    }
    return details

def get_total_earnings():
    fees = {
        'wow': 0,
        'xmr': 0,
    }
    prices = get_prices()
    swaps = Swap.query.filter(Swap.completed == True)
    for swap in swaps:
        fees[swap.send_coin()] += swap.fee_amount_atomic
    wow_amt = wownero.as_real(wownero.from_atomic(fees['wow']))
    xmr_amt = monero.as_real(monero.from_atomic(fees['xmr']))
    fee_totals = perform_conversion(wow_amt, xmr_amt)
    return fee_totals

def get_broken_down_earnings():
    fees = {
        'wow': {},
        'xmr': {}
    }
    swaps = Swap.query.filter(Swap.completed == True)
    for swap in swaps:
        d = arrow.get(swap.date).format('YYYY-MM')
        _t = fees[swap.send_coin()]
        if d not in _t:
            _t[d] = 0
        _t[d] += swap.fee_amount_atomic

    for coin in fees:
        for d in fees[coin]:
            if coin == 'wow':
                fees[coin][d] = float(wownero.from_atomic(fees[coin][d]))
            else:
                fees[coin][d] = float(monero.from_atomic(fees[coin][d]))
    return fees
