# -*- coding: utf-8 -*-
import json

from dajaxice.decorators import dajaxice_register
from exercises.models import Exercise
from tasks.models import ExerciseTaskPosition
from users.decorators import require_apprentice
from utils.general import progress_percent


@require_apprentice
@dajaxice_register
def exercise_done(request, exercise_task_position_id):
    try:
        etp = ExerciseTaskPosition.objects.active().get(id=exercise_task_position_id)
        etp.exercise.apprentices.add(request.user)
        task_all_exercises_count = etp.task.all_exercises_count()
        task_done_exercises_count = etp.task.done_exercises_count(request.user)
        if task_all_exercises_count == task_done_exercises_count:
            status = 'all_done'
        else:
            status = 'done'
        progress = progress_percent(task_done_exercises_count, task_all_exercises_count)
    except Exercise.DoesNotExist:
        status = 'error'
        progress = ''

    return json.dumps({'status': status, 'progress': progress})
