# -*- coding: utf-8 -*-

from decimal import Decimal as D, ROUND_UP
from .models import Currency as C
from .conf import SESSION_KEY



def convert(amount, from_code, to_code, quantize_to=D("0.01")):
    if from_code == to_code:
      return amount

    from_, to = C.active.get(code=from_code), C.active.get(code=to_code)

    amount = D(amount) * (to.factor / from_.factor)
    return amount.quantize(quantize_to, rounding=ROUND_UP)


def calculate(price, *args, **kwargs):
    default_code = C.active.default().code
    return convert(price, default_code, *args, **kwargs)


def get_currency_code(request):
    for attr in ('session', 'COOKIES'):
        if hasattr(request, attr):
            try:
                return getattr(request, attr)[SESSION_KEY]
            except KeyError:
                continue

    # fallback to default...
    try:
        return C.active.default().code
    except C.DoesNotExist:
        return None  # shit happens...

@@ -127,16 +127,89 @@
 N_KEY%0A%0A%0A
+def get_active_currencies_qs():%0A    return C.active.defer('info').all()%0A%0A
 %0Adef con
@@ -262,16 +262,25 @@
 (%220.01%22)
+, qs=None
 ):%0A    i
@@ -305,24 +305,26 @@
 code:%0A      
+ 
+ 
 return amoun
@@ -326,16 +326,76 @@
 amount%0A%0A
+    if qs is None:%0A        qs = get_active_currencies_qs()%0A%0A
     from
@@ -402,24 +402,18 @@
 _, to = 
-C.active
+qs
 .get(cod
@@ -426,24 +426,18 @@
 _code), 
-C.active
+qs
 .get(cod
@@ -581,16 +581,25 @@
 e(price,
+ to_code,
  *args, 
@@ -609,16 +609,153 @@
 wargs):%0A
+    try:%0A        qs = args%5B1%5D%0A    except IndexError:%0A        qs = kwargs.get('qs', get_active_currencies_qs())%0A        kwargs%5B'qs'%5D = qs%0A
     defa
@@ -765,24 +765,18 @@
 _code = 
-C.active
+qs
 .default
@@ -818,24 +818,33 @@
 efault_code,
+ to_code,
  *args, **kw

improve utils support for command arguments and qs caching