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

"""
Простенький скрипт для построения csvindex.
"""

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


import sys
import stocks3
from stocks3.core.source import SourceLoader
from stocks3.core.config import parse_xml
from stocks3.export.exporter import Exporter
from stocks3.core.default import Default
from stocks3.export.opts import ExporterOpts
from stocks3.share.savethroughtmp import save_through_tmp


DEF_EXPORTER_CONFIG = "config/exporter.xml"
DEFAULT_XML = "config/default-db.xml"


class ExportCsvIndexOpts(ExporterOpts):
    def __init__(self, argv):
        self.output_filename = None
        ExporterOpts.__init__(self, argv, 'o:')
        if self.output_filename is None:
            print("Error: expected output filename")
            self.usage()
            exit(4)

    def usage(self):
        print("s3csvindex [-v] [-t] -c [default-config] -o output-regions-xml")

    def handle_opts(self, optlist):
        optlist = ExporterOpts.handle_opts(self, optlist)
        unhandled = []
        for opt, value in optlist:
            if opt in ["-o"]:
                self.output_filename = value
            else:
                unhandled.append( (opt, value) )
        return unhandled


def make_exporter(sources, output_category_list, export_quotes=None):
    default = Default(DEFAULT_XML)
    tree = parse_xml(DEF_EXPORTER_CONFIG)
    root = tree.getroot()
    return Exporter(tree, root, default, sources, output_category_list, export_quotes)


def main():
    stocks3.load_modules()
    opts = ExportCsvIndexOpts(sys.argv)
    # Создаем экспортер, он нам отдаст читалку, а читалка нам отдаст базу данных

    loader = SourceLoader()
    sources = loader.get_active_sources()

    exporter = make_exporter(sources, ["csvindex"])
    index = []
    for quote in exporter.list_of_quotes_for_export():
        if quote.has_flag("csvindex"):
            index.append(str(quote.quote_id))
        if quote.alias_quote and quote.alias_quote.has_flag("csvindex"):
            index.append(str(quote.alias_name))
    save_through_tmp(".", opts.output_filename,
                     "\n".join(sorted(index, key=lambda x: int(x))),
                     "stocks3_csvindex")


if __name__ == "__main__":
    main()
