from rest_framework import serializers
from .models import *
from exercise.serializers import ExerciseSerializer
from registered_user.serializers import GetRegisteredUserSerializer

class WorkoutExerciseSerializer(serializers.ModelSerializer):
    exercise = ExerciseSerializer(read_only=True)
    duration_audio = serializers.ReadOnlyField()
    weight_audio = serializers.ReadOnlyField()

    class Meta:
        model = WorkoutExercise
        fields = ('workout', 'exercise','weight','reps','duration','duration_audio','weight_audio', 'created_at',)



class CompleteWorkoutSerializer(serializers.ModelSerializer):
    class Meta:
        model = CompletedWorkout
        exclude = ['registered_user']

    def create(self, validated_data):
        registered_user_id = self.context.get("registered_user")
        registered_user = RegisteredUser.objects.get(id=registered_user_id)
        completed_workout = CompletedWorkout.objects.create(
            registered_user=registered_user,
            workout=validated_data['workout'],
            difficulty=validated_data['difficulty'],
            total_time=validated_data['total_time'],
            workout_start_time=validated_data['workout_start_time'],
            notes=validated_data['notes'],
            total_calories=validated_data['total_calories']
        )
        completed_workout.save()
        return completed_workout

class WorkoutSerializer(serializers.ModelSerializer):
    # exercise = WorkoutExerciseSerializer(source='workout_exercise_workout', many=True)
    registered_user = GetRegisteredUserSerializer(many=False, read_only=True)

    class Meta:
        model = Workout
        fields = '__all__'
        # depth = 1

class WorkoutDetailSerializer(serializers.ModelSerializer):
    exercises = serializers.SerializerMethodField()
    registered_user = serializers.SerializerMethodField()

    class Meta:
        model = Workout
        fields = ('id', 'name', 'description', 'exercises', 'registered_user')
        depth = 1
   
    def get_exercises(self, obj): 
        objs = WorkoutExercise.objects.filter(workout=obj)
        data = WorkoutExerciseSerializer(objs, many=True).data
        return data
    
    def get_registered_user(self, obj):
        objs = RegisteredUser.objects.get(pk=obj.registered_user.pk)
        data = GetRegisteredUserSerializer(objs, many=False).data
        return data

class GetCompleteWorkoutSerializer(serializers.ModelSerializer):
    workout = WorkoutSerializer(many=False, read_only=True)

    class Meta:
        model = CompletedWorkout
        exclude = ['registered_user']

class POSTCompleteWorkoutSerializer(serializers.ModelSerializer):
    class Meta:
        model = Workout
        exclude = ['registered_user']