from __future__ import division
from __future__ import unicode_literals

from decimal import Decimal

import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

from .models import ConversionRate

BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
    API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
    raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')


class ExchangeRates(object):

    def __init__(self, rates, default_currency=None):
        self.rates = rates
        self.default_currency = (
            default_currency or settings.DEFAULT_CURRENCY)

    def __getitem__(self, item):
        rate = self.rates[item]
        return rate / self.rates[self.default_currency]


def get_latest_exchange_rates():
    response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
    response.raise_for_status()
    exchange_data = response.json(parse_int=Decimal, parse_float=Decimal)
    return ExchangeRates(rates=exchange_data['rates'])


def update_conversion_rates():
    exchange_rates = get_latest_exchange_rates()
    conversion_rates = ConversionRate.objects.all()
    for conversion_rate in conversion_rates:
        new_exchange_rate = exchange_rates[conversion_rate.to_currency]
        conversion_rate.rate = new_exchange_rate
        conversion_rate.save(update_fields=['rate'])
    return conversion_rates

@@ -484,84 +484,40 @@
 )%0A%0A%0A
-class ExchangeRates(object):%0A%0A    def __init__(self, rates, default_
+def extract_rate(rates, 
 currency
 =Non
@@ -516,42 +516,32 @@
 ency
-=None
 ):%0A    
-    self.
+base_
 rate
-s
  = rates
 %0A   
@@ -540,176 +540,40 @@
 ates
-%0A        self.default_currency = (%0A            default_currency or settings.DEFAULT_CURRENCY)%0A%0A    def __getitem__(self, item):%0A        rate = self.rates%5Bitem%5D%0A  
+%5Bsettings.DEFAULT_CURRENCY%5D%0A
     
-  
 retu
@@ -583,44 +583,31 @@
 rate
- / self.rates%5Bself.default_currency%5D
+s%5Bcurrency%5D / base_rate
 %0A%0A%0Ad
@@ -751,23 +751,14 @@
     
-exchange_data =
+return
  res
@@ -812,63 +812,8 @@
 al)%0A
-    return ExchangeRates(rates=exchange_data%5B'rates'%5D)%0A
 %0A%0Ade
@@ -1021,21 +1021,76 @@
 = ex
-change_rates%5B
+tract_rate(exchange_rates,%0A                                         
 conv
@@ -1112,17 +1112,17 @@
 currency
-%5D
+)
 %0A       

Make rates parsing more readable