# -*- coding: utf8 -*-
import logging
import traceback as tb
from os.path import dirname, join
from shutil import rmtree
from time import sleep
from startrek_client import Startrek

from robot import filters, secret
from ta_task import TaTask
from errs import TaTaskError
from utils import get_ta_version, 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: {}'.format(', '.join(test_keys)))
        issues = [st_client.issues[key] for key in test_keys]

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

    return issues


def proceed_robot(test_keys=None):
    test_mode = True if test_keys else False
    logger.info('Starting...')
    if not test_mode:
        try:
            for i in range(3):
                send_mail(from_='robot-ta-report@yandex-team.ru', password=secret['password'],
                          subject=u'Робот запущен!', message=get_ta_version(),
                          to=['vbatraev@yandex-team.ru'])
                break
        except:
            logger.exception('Oops!')

    while True:
        for issue in check_queue(test_keys):
            try:
                task = TaTask(test_mode, issue)
                task.calculate_ta()

            except TaTaskError as ta_task_err:
                logger.error(ta_task_err.msg)
                try:
                    rmtree(join(dirname(dirname(__file__)), issue.key))
                except:
                    pass

            except KeyboardInterrupt:
                logger.info('Keyboard interrupt')
                try:
                    rmtree(join(dirname(dirname(__file__)), issue.key))
                except:
                    pass

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

                try:
                    rmtree(join(dirname(dirname(__file__)), issue.key))
                except:
                    pass

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