# -*- coding: utf-8 -*-
import logging
from os import remove
from os.path import dirname, join
from startrek_client import Startrek
from time import sleep
import traceback
from robot import SECRET, ST_FILTERS as FILTERS
from cpa_data_task.task_class import CPADataTask
from errs import (
    ClickHouseError,
    MaxRetriesError,
    TaskError,
    YQLError
)

logger = logging.getLogger(__name__)


def check_queue(test_keys=None):
    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'.format(len(issues)))

    return issues


def run_robot(test_keys=None):
    test_mode = True if test_keys else False
    logger.info('Go!')
    while True:
        for issue in check_queue(test_keys):
            try:
                task = CPADataTask(test_mode, issue)
                task.load_data()
                task.paste_result()

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

            except (TaskError, YQLError):
                pass

            except MaxRetriesError as exc:
                logger.error('{}: {}'.format(issue.key, exc.message))
                if not test_mode:
                    issue.comments.create(text='Достигнуто максимальное количество запросов к ClickHouse.',
                                          summonees=['orlovgb', 'zedlaa'])
                    issue.transitions['need_info'].execute()

            except ClickHouseError as exc:
                logger.error('{}: {}'.format(issue.key, exc.message))
                query_path = join(dirname(dirname(__file__)), '{}_query.txt'.format(issue.key))
                with open(query_path, 'w') as fd:
                    fd.write(exc.query)
                if not test_mode:
                    issue.comments.create(text=u'При выполнении запроса к ClickHouse возникла ошибка. <{Подробнее:'
                                               u'\n%%%%\n%s\n%%%%'
                                               u'}>' % exc.message,
                                          attachments=[query_path],
                                          summonees=['orlovgb', 'zedlaa'])
                    remove(query_path)
                    issue.transitions['need_info'].execute()

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

        if not test_mode:
            timeout = 15
            logger.info('Sleeping for {} seconds...'.format(timeout))
            sleep(timeout)

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