# -*- coding: utf-8 -*-
"""
Транспорт для интефакса
"""
import json
import requests
from stocks3.core.factories import transports
from stocks3.core.transport import Transport
from stocks3.core.config import JSONConfigurable
from stocks3.core.utils import force_decode
import time

urls = {
    'USD': 'https://www.rbc.ru/money_graph/latest/59111/?_={}',
    'EUR': 'https://www.rbc.ru/money_graph/latest/59090/?_={}',
    # 'Brent': 'https://www.rbc.ru/money_graph/latest/83350/?_={}',
    'Brent': 'https://www.rbc.ru/money_graph/latest/181206/?_={}',
    'MOEX': 'https://www.rbc.ru/money_graph/latest/61867/?_={}',
}


class RbcTransport(Transport, JSONConfigurable):
    """
    """
    def transfer(self, place):
        Transport.transfer(self, place)

        to_place = {}
        for quote, url in urls.items():
            r = requests.get(url.format(int(time.time() * 1000)))
            if r.status_code != 200:
                raise IOError('Bad status from rbc.ru - {0} : {1}'.format(r.status_code, r.content))
            content = force_decode(r.content)
            result = json.loads(content)

            try:
                onepack = sorted(result['data'], key=lambda v: v['date'], reverse=True)[:1][0]
                to_place[quote] = onepack
            except KeyError as ke:
                print(ke)
                raise IOError('Bad rbc.ru content - {}'.format(ke))
        place.store(json.dumps(to_place))


transports.register("stocks3.transports.rbc", RbcTransport)
