from datetime import datetime

from celery import current_app


def list_tasks():
    current_app.loader.import_default_modules()
    return (t for name, t in current_app.tasks.items()
            if not name.startswith('celery.'))


def list_running():
    inspector = current_app.control.inspect()

    def format_task(task):
        ts = task['time_start']
        try:
            task['time_start_humanized'] = (
                datetime.fromtimestamp(ts).isoformat()
            )
        except TypeError:
            pass
        return task
    return {
        key: {
            host: list(map(format_task, tasks))
            for host, tasks
            in (getattr(inspector, key)() or {}).items()
        }
        for key in ('active', 'scheduled', 'reserved')
    }


def run_task(name, args, kwargs, **options):
    current_app.loader.import_default_modules()
    cls = current_app.tasks[name]
    return cls.apply_async(args, kwargs, **options)


def get_result(task_id):
    return current_app.AsyncResult(task_id)


def list_finished():
    tasks = current_app.backend.TaskModel.objects.order_by('-date_done')[:50]
    return [
        {
            k: str(v)
            for k, v in t.to_dict().items()
        }
        for t in tasks
    ]
