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

"""
Подготавливаем SQL для средних значений по бензину.
"""

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

import stocks3
from stocks3.core.config import parse_xml
from stocks3.share.config import load_standart_default, make_source_with_file
from stocks3.core.default import Default

def output_header():
    """
    Шапка запроса.
    """
    return "REPLACE INTO stocks (id, src, s_date, s_time, value, sell_value, region, s_unixtime)\nVALUES"

def price_to_sql(source, price):
    return "  (%s, %s, '%s', '%s', %s, NULL, %s, %s)" % (
        price.quote.quote_id, source.weight, price.date.strftime("%Y-%m-%d"), price.date.strftime("%H:%M:%S"),
        price.value, price.region, int(price.unixtime))


if __name__ == "__main__":
    import sys
    stocks3.load_modules()
    default = load_standart_default()
    source = make_source_with_file("catalog/sources/transitcard-countries.xml", default)
    print(output_header())
    output = None
    for fn in sys.argv[1:]:
        place = default.getDefaultPlace()
        place.filename = fn
        for price in source.parser.parse(place):
            if output is not None:
                print(output+",")
            price = source.run_calculators(price)
            output = price_to_sql(source, price)
    if output is not None:
        print(output + "\n")

