# -*- coding: utf-8 -*-
"""
Помогает разобраться в настройках (выдает информацию о котировке).
"""
import argparse
import stocks3
import logging
from stocks3.core.default import Default
from stocks3.core.source import SourceLoader
from stocks3.readers.db import DBReader

from stocks3.share.quotesourcemap import get_quote_source_multimap
from stocks3.share.timezone import get_active_timezones
import time


DEFAULT_XML = "config/default-db.xml"

# template_notfound = '''Quote {{quote_id}} not found.'''
# template_disabled = '''Quote {{quote_id}} is disabled.'''
# template_quote = '''*** Quote {{quote.quote_id}} - "{{quote.name}}" [{{source_name}}]
#     quote-name = {{quote.name}}
#     numerator = {{quote.numerator.stock}} ({{quote.numerator.scale}})
#     denominator = {{quote.denominator.stock}} ({{quote.denominator.scale}})
#     export name = {{quote.export.name}}
#     news title = {{quote.export.news_title}}
#     name readable = {{quote.export.name_readable}}
# '''


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("quotes", nargs='+', type=int, help="Quotes list")
    args = parser.parse_args()

    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger('QINFO')

    stocks3.load_modules()

    default = Default(DEFAULT_XML)
    loader = SourceLoader()
    source_map = get_quote_source_multimap([x[1] for x in loader.get_active_sources()])

    for quote_id in args.quotes:
        standart_quote = default.quotes_config.get_quote_by_id(quote_id)
        if standart_quote is None:
            print("Quote {0} not found.".format(quote_id))
            continue
        # Подгружаем экспортную информацию
        quote = standart_quote

        source_list = source_map.get(quote.name, None)
        source_name = "None"
        if source_list is not None:
            source_name = ', '.join(['{}({})'.format(source.sourceId, source.weight) for source in source_list])

        print("*** Quote %s - \"%s\" [%s]" % (quote.quote_id, quote.name, source_name))
        print("    quote-name = %s" % quote.name)
        print("    numerator = %s (%s)" % (quote.numerator.stock, quote.numerator.scale))
        print("    denominator = %s (%s)" % (quote.denominator.stock, quote.denominator.scale))
        print("    name = %s" % quote.export["name"])
        print("    news_title = %s" % quote.export["news_title"])
        print("    name_readable = %s" % quote.export["name_readable"])
        print()

        # Выводим информацию о временных зонах
        if source_list is None:
            print("T>  Quote is disabled.")
        else:
            for map_name, map_, timezone in get_active_timezones(source_list[0], quote):
                region = map_.getQuoteRegion(quote)
                print("T>  Timezone %s %s" % (map_name, timezone))
                quote_info = source_list[0].parser.getQuoteInfo(region, quote)
                print()
                for key, value in sorted(quote_info.items()):
                    print("I %s>  %s=%s" % (quote.quote_id, key, str(value)))
        print()

        # Выводим немножко данных
        reader = DBReader(None, None, None)
        allprices = [x for x in reader.read(1, quote)]
        if len(allprices) == 0 or len(allprices[0][1]) == 0:
            print("    Last\t%s\t?\tnothing" % quote.quote_id)
        else:
            for quote, prices in allprices:
                for region, data in prices.items():
                    if len(data) == 0:
                        print("    Last\t%s\t?\tnothing" % quote.quote_id)
                    else:
                        if data[0].is_dual_price:
                            sell_value = data[0].sell.value
                        else:
                            sell_value = 0.0
                        print("    Last\t%s\t%s\t%s\t%s\t%s\t%s\t%s" % (
                            quote.quote_id, region, data[0].unixtime, time.mktime(data[0].date.timetuple()),
                            data[0].date,
                            data[0].buy.value, sell_value))
            print()
            print()


if __name__ == "__main__":
    main()
