# -*- coding: utf-8 -*-
from datetime import timedelta
import logging
from multiprocessing.dummy import Pool
from threading import Thread
from time import sleep
from Queue import Queue

from issues import check_queue, FBTask, task_worker
from utils import send_mail

logger = logging.getLogger(__name__)


def run_robot(debug=False):
    logger.info('Ask it!')

    pool = DeadPool()
    pool.start()
    if not debug:
        send_mail(to=['leroy@yandex-team.ru', ], subject=u'Робот запущен!', message=u'')

    while True:
        for issue in check_queue(debug):
            try:
                if issue.key not in pool.issues:
                    pool.issues.append(issue.key)
                    pool.queue.put(FBTask(debug, issue))

            except Exception:
                logger.exception('Oops!')

        timeout = 60 * 60 * 6
        logger.info('Check queue in %s', str(timedelta(seconds=round(timeout))))
        sleep(timeout)


class DeadPool(Thread):
    def __init__(self):
        super(DeadPool, self).__init__()
        self.queue = Queue()
        self.pool = Pool()

        self.issues = []

    def generate_tasks(self):
        while True:
            task = self.queue.get()
            logger.debug('%s: yield', task.issue.key)
            yield task

    def run(self):
        while True:
            for task in self.pool.imap_unordered(task_worker, self.generate_tasks()):
                self.issues.remove(task.issue.key)
                logger.debug('%s: completed', task.issue.key)


if __name__ == '__main__':
    run_robot()
