# -*- coding: utf-8 -*-
from __future__ import division

from datetime import datetime
from logging import getLogger
from os.path import abspath, basename
from sys import exit

import work_queue as wq

from yerba.core import TASK_DONE
from yerba.services import Service

logger = getLogger('yerba.workqueue')
name = "yerba"
MAX_OUTPUT = 65536

def get_task_info(task):
    dateformat="%d/%m/%y at %I:%M:%S%p"
    DIV = 1000000.0

    dt1 = datetime.fromtimestamp(task.submit_time / DIV)
    start_time = dt1.strftime(dateformat)

    dt2 = datetime.fromtimestamp(task.finish_time / DIV)
    finish_time = dt2.strftime(dateformat)
    execution_time = task.cmd_execution_time / DIV

    return {
        'cmd' : task.command,
        'started' : start_time,
        'ended' : finish_time,
        'elapsed' : execution_time,
        'taskid' : task.id,
        'returned' : task.return_status,
        'output' : repr(task.output[:MAX_OUTPUT]),
    }

class WorkQueueService(Service):
    name = "workqueue"
    group = "scheduler"

    def __init__(self, config, notifier):
        self.tasks = {}
        self.notifier = notifier

        try:
            self.project = config['project']
            self.catalog_server = config['catalog_server']
            self.catalog_port = int(config['catalog_port'])
            self.port = int(config['port'])
            self.log = config['log']

            if config['debug']:
                wq.set_debug_flag('all')
        except KeyError:
            logger.exception("Invalid workqueue configuration")
            exit(1)

    def initialize(self):
        '''
        Initializes work_queue for scheduling workers.

        A new work_queue will be created if an existing queue is not connected
        on the port. If an existing queue is running then the process will exit.
        '''
        try:
            self.queue = wq.WorkQueue(name=self.project, catalog=True, port=-1)
            self.queue.specify_catalog_server(self.catalog_server,
                    self.catalog_port)
            self.queue.specify_log(self.log)

            logger.info('WORKQUEUE %s: Starting work queue on port %s',
                    self.project, self.queue.port)
        except Exception:
            logger.exception("The work queue could not be started")
            exit(1)

    def stop(self):
        '''
        Removes all jobs from the queue and stops the work queue.
        '''
        logger.info('WORKQUEUE %s: Stopping work queue on port %s',
                self.project, self.queue.port)
        self.queue.shutdown_workers(0)

    def schedule(self, iterable, name, priority=None):
        '''
        Schedules jobs into work_queue