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

"""
Скрипт, запускающий процесс обработки данных.

В качестве аргументов могут быть указаны имена источников, из которых данные
нужно забрать.
"""
import stocks3
import argparse
import logging
from stocks3.core.source import SourceLoader
from stocks3.share import messages


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose", help="Verbose output", action='store_true', required=False)
    parser.add_argument("-t", "--tracebacks", help="Print tracebacks", action='store_true', required=False)
    parser.add_argument("-c", "--config", help="Default configurator file", required=False)
    parser.add_argument("-i", "--inactive", help="Run inactive sources", action='store_true', required=False)
    parser.add_argument("-f", "--force", nargs='+', help="Disable checks for selected quotes", required=False)
    parser.add_argument("-s", "--source_dir", help="Directory with sources", required=False)
    parser.add_argument("--skip_cache", help="Disable source cache check", action='store_true', required=False)
    parser.add_argument("sources", nargs='*', help="Sources list")
    args = parser.parse_args()

    logging.basicConfig(level=logging.DEBUG if args.verbose else logging.WARNING)
    logger = logging.getLogger('IMPORT')

    stocks3.load_modules()
    loader = SourceLoader(args.sources, args.inactive)
    sources = loader.get_active_sources()

    for source_name, source in sources:
        messages.verbose("Transfer %s\n" % source_name)
        try:
            try:
                source.transfer(skip_cache=args.skip_cache)
            except Exception as e:
                logger.error('Source:', source_name, 'Exception: ', e)
            finally:
                source.clean()
        except Exception as e:
            logger.error('Source:', source_name, 'Exception while clean: ', e)


if __name__ == "__main__":
    main()

