from django.contrib.auth import get_user_model
from rest_framework import serializers

from verify_trusted.companies.api.serializers import SocialSerializer
from verify_trusted.companies.history_types import HistoryType, HistoryTypeSymbol
from verify_trusted.companies.models import Company, Review
from verify_trusted.reviews.api.serializers import ReviewSourceSerializer
from verify_trusted.utils.serializers import DynamicFieldsModelSerializer

User = get_user_model()


class UserCompanyHistorySerializer(DynamicFieldsModelSerializer):
    class Meta:
        model = User
        fields = '__all__'


class CompanyHistorySerializer(serializers.ModelSerializer):
    history_id = serializers.ReadOnlyField()
    history_date = serializers.DateTimeField(read_only=True)
    history_type = serializers.SerializerMethodField()
    history_user = UserCompanyHistorySerializer(
        fields=[
            'id',
            'username',
            'name',
        ]
    )
    user = UserCompanyHistorySerializer(
        fields=[
            'id',
            'username',
            'name',
        ]
    )
    socials = SocialSerializer(many=True, required=False)

    class Meta:
        model = Company
        exclude = ('search_vector',)

    def get_history_type(self, obj):  # noqa
        history_type = obj.history_type
        history_change_reason = obj.history_change_reason
        if history_change_reason == HistoryType.CLAIMED:
            return HistoryType.CLAIMED
        if history_type == HistoryTypeSymbol.CREATED:
            return HistoryType.CREATED
        if history_type == HistoryTypeSymbol.CHANGED:
            return HistoryType.CHANGED
        if history_type == HistoryTypeSymbol.DELETED:
            return HistoryType.DELETED
        return history_type


class ReviewHistorySerializer(serializers.ModelSerializer):
    history_id = serializers.ReadOnlyField()
    history_date = serializers.DateTimeField(read_only=True)
    history_type = serializers.SerializerMethodField()
    source = ReviewSourceSerializer()

    class Meta:
        model = Review
        fields = '__all__'

    def get_history_type(self, obj):  # noqa
        history_type = obj.history_type
        if history_type == HistoryTypeSymbol.CREATED:
            return HistoryType.CREATED
        if history_type == HistoryTypeSymbol.CHANGED:
            return HistoryType.CHANGED
        if history_type == HistoryTypeSymbol.DELETED:
            return HistoryType.DELETED
        return history_type
