from rest_framework import serializers

from apps.billboard.models import Line, Post
from apps.lyric.models import User


class LineSerializer(serializers.ModelSerializer):
    text = serializers.CharField()

    def validate_text(self, value):
        post = self.context["post"]
        if post.lines.filter(text=value).exists():
            raise serializers.ValidationError("duplicate")
        return value

    class Meta:
        model = Line
        fields = ["id", "text"]

class PostSerializer(serializers.ModelSerializer):
    name = serializers.ReadOnlyField(source="title")
    url = serializers.CharField(source="get_absolute_url", read_only=True)
    lines = LineSerializer(many=True, read_only=True)

    class Meta:
        model = Post
        fields = ["id", "name", "url", "lines"]

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "username"]
