# -*- coding: utf-8 -*-
import logging
import traceback as tb
from time import sleep
from startrek_client import Startrek

from robot import TOKEN
from task_worker import TaskWorker, TaskWorkerError
from presentation.ppt_maker import make_ppt

logger = logging.getLogger(__name__)


def check_queue(test_keys=None):
    st_client = Startrek(useragent='', token=TOKEN)

    if test_keys:
        logger.info('Use test_keys: {}'.format(', '.join(test_keys)))
        issues = [st_client.issues[key] for key in test_keys]

    else:
        filters = {
            'queue': 'BTZFIN',
            'assignee': 'me()',
            'status': {'id': 1}
        }

        logger.info('Use filters: {}'.format(filters))
        issues = st_client.issues.find(filter=filters, order=['-created'])

    logger.info('{} issues in BTZFIN'.format(len(issues)))

    return issues


def mr_robot(test_keys=None):
    test_mode = True if test_keys else False
    logger.info('Go!')

    while True:
        for issue in check_queue(test_keys):
            task = None

            try:
                task = TaskWorker(test_mode, issue)
                task.run_categories()
                task.pptx_path = make_ppt(task)

                task.paste_results()

            except TaskWorkerError as tw_err:
                logger.error(tw_err.msg)
            except KeyboardInterrupt:
                logger.info('Keyboard interrupted')
                break
            except:
                logger.exception('{}: Oops!'.format(issue.key))
                if not test_mode:
                    issue.comments.create(text='Что-то сломалось...<{Подробнее:'
                                               '\n%%%%\n%s\n%%%%'
                                               '}>' % tb.format_exc(),
                                          summonees=['leroy'])
                if task:
                    task.drop_results()

                if not test_mode:
                    issue.transitions['need_info'].execute()

        if not test_mode:
            logger.info('Sleeping for 30 seconds...')
            sleep(30)
        else:
            logger.info('Breaking test_mode...')
            break
