from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import QuerySet

from oscar.core.loading import get_model, is_model_registered


class OcyanJSONEncoder(DjangoJSONEncoder):
    """
    Encoding support for various objects that are used in ocyan projects.
    """

    def default(self, o):
        if hasattr(o, "to_json"):
            return o.to_json()

        if hasattr(o, "json"):
            return o.json()

        if isinstance(o, QuerySet):
            return list(o)

        if is_model_registered("catalogue", "AttributeOption"):
            AttributeOption = get_model("catalogue", "AttributeOption")
            if isinstance(o, AttributeOption):
                return o.option

        return super().default(o)
