#!/usr/bin/env python3
# coding: utf-8

import sys
from libs import xmltodict
import json
from collections import OrderedDict


def pretty_print(somedict):
    print(json.dumps(somedict, indent=4, ensure_ascii=False))


def format_stock(stock):
    for key, value in list(stock.items()):
        if stock[key] is None:
            stock.pop(key)

    stock['name'] = stock.pop('@name')
    stock['id'] = int(stock.pop('@inner-id'))
    stock['numerator']['stock'] = stock['numerator'].pop('@stock')
    if '@scale' in stock['numerator']:
        scale = int(stock['numerator'].pop('@scale'))
        if scale != 1:
            stock['numerator']['scale'] = scale

    if stock['denominator']['@stock'] == 'Pseudo':
        stock.pop('denominator')

    if 'denominator' in stock:
        stock['denominator']['stock'] = stock['denominator'].pop('@stock')
        if '@scale' in stock['denominator']:
            scale = int(stock['denominator'].pop('@scale'))
            if scale != 1:
                stock['denominator']['scale'] = scale
    if 'group' in stock:
        stock['group']['order'] = int(stock['group'].pop('@order'))
        stock['group']['text'] = stock['group'].pop('#text')

    if 'ishot' in stock:
        stock['ishot']['klimit'] = int(stock['ishot'].pop('klimit'))
        stock['ishot']['percent'] = bool(stock['ishot'].pop('percent'))

    if 'skip-zero-value' in stock:
        stock['skip-zero-value'] = bool(stock['skip-zero-value'])
    if 'killed' in stock:
        stock['killed'] = bool(stock['killed'])
    if 'is-cross' in stock:
        stock['is-cross'] = bool(stock['is-cross'])
    if 'history_in_percentage' in stock:
        stock['history_in_percentage'] = bool(stock['history_in_percentage'])
    if 'is-dual' in stock:
        stock['is-dual'] = stock['is-dual'] == 'True'
    if 'precision' in stock:
        stock['precision'] = int(stock['precision'])

    for key, value in list(stock.get('export-flags', {}).items()):
        if stock['export-flags'][key] == 'False':
            stock['export-flags'].pop(key)
        elif stock['export-flags'][key] == 'True':
            stock['export-flags'][key] = True

    if 'aliases' in stock:
        stock['alias'] = int(stock.pop('aliases')['alias'])

    if 'lines' in stock:
        lines = stock.pop('lines')
        stock['lines'] = {
            lines['line'][0]['@id']: lines['line'][0]['#text'],
            lines['line'][1]['@id']: lines['line'][1]['#text'],
        }

    if 'doublegraph' in stock:
        doublegraph = stock.pop('doublegraph')
        if isinstance(doublegraph, dict):
            stock['doublegraph'] = {
                doublegraph['#text']: doublegraph['@region'],
            }
        else:
            stock['doublegraph'] = {
                doublegraph: 0
            }

    new_stock = OrderedDict()
    for key in [
        'id',
        'killed',
        'alias',
        'export-name',
        'name',
        'symbol',
        'numerator',
        'denominator',
        'index-title',
        'page-title',
        'news-title',
        'name-readable',
        'page-description',
        'precision',
        'skip-zero-value',
        'doublegraph',
        'is-cross',
        'history_in_percentage',
        'is-dual',
        'history_type',
        'stype',
        'ishot',
        'lines',
        'group',
        'export-flags',
    ]:
        if key in stock:
            new_stock[key] = stock[key]

    return new_stock


filename = sys.argv[1] if len(sys.argv) > 1 else "catalog/quotes.xml"
with open(filename) as f:
    content = f.read()
    quotes = xmltodict.parse(content)
    quotes = quotes['quotes']['quote']
    result = [format_stock(quote) for quote in quotes]

    pretty_print(result)
