import structlog
from rest_framework.decorators import api_view
from rest_framework.response import Response
from wagtail.models import Page

from vbv_lernwelt.completion.models import CircleCompletion
from vbv_lernwelt.completion.serializers import CircleCompletionSerializer
from vbv_lernwelt.learnpath.models import Circle, LearningPath
from vbv_lernwelt.learnpath.utils import get_wagtail_type

logger = structlog.get_logger(__name__)


@api_view(['GET'])
def request_circle_completion(request, circle_key):
    response_data = CircleCompletionSerializer(
        CircleCompletion.objects.filter(user=request.user, circle_key=circle_key),
        many=True,
    ).data

    return Response(status=200, data=response_data)


@api_view(['GET'])
def request_learning_path_completion(request, learning_path_key):
    response_data = CircleCompletionSerializer(
        CircleCompletion.objects.filter(user=request.user, learning_path_key=learning_path_key),
        many=True,
    ).data

    return Response(status=200, data=response_data)


@api_view(['POST'])
def mark_circle_completion(request):
    page_key = request.data.get('page_key')
    completed = request.data.get('completed', True)

    page = Page.objects.get(translation_key=page_key, locale__language_code='de-CH')
    page_type = get_wagtail_type(page.specific)
    circle = Circle.objects.ancestor_of(page).first()
    learning_path = LearningPath.objects.ancestor_of(page).first()

    cc, created = CircleCompletion.objects.get_or_create(
        user=request.user,
        page_key=page_key,
        circle_key=circle.translation_key,
        learning_path_key=learning_path.translation_key,
    )
    cc.page_type = page_type
    cc.completed = completed
    cc.save()

    response_data = CircleCompletionSerializer(
        CircleCompletion.objects.filter(user=request.user, circle_key=circle.translation_key),
        many=True,
    ).data

    logger.debug(
        'page completed',
        label='completion_api',
        circle_key=circle.translation_key,
        circle_title=circle.title,
        page_key=page_key,
        page_type=page_type,
        page_title=page.title,
        user_id=request.user.id,
    )

    return Response(status=200, data=response_data)
