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

"""
Обрабатываем выдачу ds.ifx для составления карты банков.

Для работы нужен старый конфиг banks.rating.prepare.xml.
"""

__author__ = "Zasimov Alexey"
__email__ = "zasimov-a@yandex-team.ru"


import sys
from stocks3.core.config import parse_xml

def load_inner_ids():
    """
    Загружает данные из старого конфига.
    """
    inner_id = {}
    tree = parse_xml("../banks.rating.prepare.xml")
    for node in tree.findall("id-map/item"):
        inner_id[int(node.get("from"))] = int(node.get("to"))
    return inner_id

def generate_quote(id, name):
    print('<quote name="%s" inner-id="%s">' % (name.encode("utf-8"), id))
    print('    <numerator stock="%s"/>' % name.encode("utf-8"))
    print('    <denominator stock="%s"/>' % 'RUB')
    print('</quote>')

def generate_stock(name):
    print('<stock name="%s" unit="пункт"/>' % name.encode("utf-8"))

def generate_quotes(tree):
    dup = {}
    names = {}
    inner_id = load_inner_ids()
    for node in tree.findall("ITEM"):
        node_id = int(node.get("id"))
        name = node.get("nickname")
        if node_id in dup:
            continue
        names[name] = node_id
        dup[node_id] = 1
    for name, name_id in sorted(names.items()):
        try:
            generate_quote(inner_id[name_id], name)
        except KeyError:
            sys.stderr.write("%s for %s\n" % (name_id, name.encode("utf-8")))

    for name in sorted(names.keys()):
        generate_stock(name)

def main(argv):
    tree = parse_xml("../ds.ifx.banks.rating.txt")
    generate_quotes(tree)


if __name__ == "__main__":
    main(sys.argv[1:])

