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

"""
Модуль для разбора параметров комантной строки экспортера.

Добавлен флаг -e - указывается конфигурация экспортера.
"""

import stocks3.share.opts

from stocks3.core.exception import S3Exception, throw_only
from stocks3.core.config import parse_xml
from stocks3.export.exporter import Exporter

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


class S3ExportError(S3Exception):
    STAGE = "export"


class ExporterOpts(stocks3.share.opts.Opts):
    DEF_EXPORTER_CONFIG = "config/exporter.xml"

    def __init__(self, argv, additional_format=""):
        self.exporter_config = self.DEF_EXPORTER_CONFIG
        self.output_category_list = []
        self.export_quotes = []
        stocks3.share.opts.Opts.__init__(self, argv, additional_format + 'e:f:q:')

    def handle_opts(self, optlist):
        optlist = stocks3.share.opts.Opts.handle_opts(self, optlist)
        unhandled = []
        for opt, value in optlist:
            if opt in ["-e"]:
                self.exporter_config = value
            elif opt in ["-f"]:
                self.output_category_list = [s.strip() for s in value.split(',')]
            elif opt in ["-q"]:
                self.export_quotes = [int(x.strip()) for x in value.split(',')]
            else:
                unhandled.append((opt, value))
        return unhandled

    @throw_only(S3ExportError)
    def makeExporter(self, sources):
        tree = parse_xml(self.exporter_config)
        root = tree.getroot()
        return Exporter(tree, root, self.default, sources, self.output_category_list, self.export_quotes)

    def usage(self):
        print("s3export [-v] [-t] [-d default-xml] [-s sources-dir] [-e exporter-config] [-q quotes-list] [sources]")
        print("Flags and options:")
        print("   -e - export configuration")
        print("   -v - verbose")
        print("   -t - traceback print")
        print("   -f - categories list")
        print("   -q - export quotes from list (only)")
