from celery.result import AsyncResult
from django.contrib.auth.decorators import login_required
from rest_framework.decorators import api_view
from rest_framework.response import Response

from console.serializers import CelerySerializer
from core.decorators import log_url


@log_url
@login_required
@api_view(('GET',))
def check_task_state(request, task_id):
    """ Check that celery task is finished
    :param task_id: Celery task ID
    """
    result = AsyncResult(task_id)
    if result.successful():
        serializer = CelerySerializer(
            data={'task_id': task_id,
                  'finished': result.successful(),
                  'result': result.get()
                  })
    else:
        serializer = CelerySerializer(
            data={'task_id': task_id,
                  'finished': result.successful(),
                  'result': result.get()})

    serializer.is_valid()
    return Response(serializer.data)
