# -*- coding: utf-8 -*-
from datetime import datetime
from dateutil.parser import parse
import logging
from multiprocessing.dummy import Pool
from time import sleep
from startrek_client import Startrek

from robot import SECRET
from robot.yql_worker import yql_worker
from utils import send_email

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:
        issues = st_client.issues.find(query=u"""Assignee: "robot-topview" AND Queue: "TOPVIEW" AND Status:
        "Открыт\"""", order=['+updated'])

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

    return issues


def generate_issues():
    logger.info('Mr Robot starting...')
    while True:
        for issue in check_queue():
            issue.transitions['start_progress'].execute()
            yield {'test_mode': False, 'issue': issue}

        check_issues_in_progress()

        time_out = 60
        logger.info('Sleeping {} seconds...'.format(time_out))
        sleep(time_out)


def check_issues_in_progress():
    logger.info('Check issues in progress')
    max_minutes = 50

    st_client = Startrek(useragent='', token=SECRET['token'])
    issues = st_client.issues.find(query=u""" Assignee: "robot-topview" AND Queue: "TOPVIEW" AND Status: "В работе\"""",
                                   order=['+updated'])

    for issue in issues:
        start_time = get_start_time(issue)
        if start_time:
            if (datetime.now().utcnow() - start_time).total_seconds() > 60 * max_minutes:
                send_email(
                    '{}@yandex-team.ru'.format(SECRET['login']), SECRET['password'],
                    to=['vbatraev@yandex-team.ru'],
                    subject=u'"В работе" более {} минут'.format(max_minutes),
                    message=u'Ссылка на задачу: https://st.yandex-team.ru/{}'.format(issue.key))


def get_start_time(issue):
    workflow_log = filter(lambda ent: ent.fields and ent.type == 'IssueWorkflow', issue.changelog)
    last_entry = None
    for entry in reversed(workflow_log):
        transitions = filter(lambda field:
                             field['field'].id == 'status' and getattr(field['to'], 'key') == 'inProgress',
                             entry.fields)
        if transitions:
            last_entry = entry
        break

    if last_entry:
        return parse(last_entry.updatedAt, ignoretz=True)
    else:
        return None


def mr_robot(test_keys=None):
    if not test_keys:
        pool = Pool(2)
        for issue in pool.imap_unordered(yql_worker, generate_issues()):
            logger.info('{}: completed'.format(issue.key))
    else:
        issues = check_queue(test_keys)
        for issue in issues:
            yql_worker({'test_mode': True, 'issue': issue})
