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

from cpa_task.task_class import TaskError
from cpa_task.tasks import FinanceTask, MKSTask, RetailTask
from robot import SECRET, ST_FILTERS
from utils import send_mail

logger = logging.getLogger(__name__)


def check_queue(test_keys):
    st_client = Startrek(useragent='', token=SECRET['token'])
    if test_keys:
        logger.info('Use test keys: %s', ', '.join(test_keys))
        issues = [st_client.issues[key] for key in test_keys]

    else:
        logger.info('Check queue: %s', ST_FILTERS)
        issues = st_client.issues.find(filter=ST_FILTERS, order=['+updated'])

        logger.info('%s issues in queue', len(issues))

    return issues


def proceed_robot(test_keys=None):
    test_mode = True if test_keys else False
    logger.info('I\'m starting...')
    if not test_mode:
        try:
            for i in range(4):
                send_mail(
                    from_='%s@yandex-team.ru' % SECRET['login'], password=SECRET['password'],
                    to=['leroy@yandex-team.ru'],
                    subject='Робот запущен', message='Строю презентации...'
                )
                break
        except:
            logger.exception('Oops!')

    while True:
        issues = check_queue(test_keys)
        for issue in issues:
            try:
                if 'retail' in issue.tags:
                    task = RetailTask(test_mode, 'retail', issue)
                elif 'standart' in issue.tags:
                    task = MKSTask(test_mode, 'standart', issue)
                elif 'finance' in issue.tags:
                    task = FinanceTask(test_mode, 'finance', issue)

                task.validate_task()
                task.make_reports()
                task.paste_results()

            except KeyboardInterrupt:
                logger.info('KeyboardInterrupt')
                break

            except TaskError as exc:
                logger.error(exc.message)
                pass

            except:
                logger.exception('%s: Oops!', issue.key)
                if not test_mode:
                    issue.comments.create(text='Что-то сломалось...<{Подробнее:'
                                               '\n%%%%\n%s\n%%%%'
                                               '}>' % tb.format_exc(),
                                          summonees=['leroy'])
                    issue.transitions['need_info'].execute()

        if test_mode:
            logger.info('Breaking test_mode...')
            break

        else:
            logger.info('Sleeping for %s seconds...', 30)
            sleep(30)
