# -*- coding: utf-8 -*-
from typing import List

from events.celery_app import app
from events.v3.errors import MissingError, ValidationError
from events.v3.schemas import OperationsInfoIn, OperationInfoOut
from events.v3.types import OperationStatus


def get_operation_info(operation_id: str) -> OperationInfoOut:
    operation = app.AsyncResult(operation_id)
    message = None
    if operation.ready():
        if operation.failed():
            status = OperationStatus.fail
            message = str(operation.info)
        else:
            status = OperationStatus.ok
    elif operation.status in ('SENT', 'STARTED', 'RECEIVED', 'RETRY'):
        status = OperationStatus.wait
    else:
        status = OperationStatus.not_running
    return OperationInfoOut(id=operation_id, status=status, message=message)


def get_operation_info_view(request, operation_id: str) -> OperationInfoOut:
    return get_operation_info(operation_id)


def get_operations_info_view(request, ids: str = None) -> List[OperationInfoOut]:
    if not ids:
        raise ValidationError([
            MissingError(loc=['ids']),
        ])
    return [get_operation_info(operation_id) for operation_id in ids.split(',')]


def post_operations_info_view(request, data: OperationsInfoIn = None) -> List[OperationInfoOut]:
    if not data:
        raise ValidationError([
            MissingError(loc=['data']),
        ])
    return [get_operation_info(operation_id) for operation_id in data.ids]
