# Imports from Django.
from django.db import models


# Imports from other dependencies.
from rest_framework.serializers import ModelSerializer


class CivicBaseQuerySet(models.QuerySet):
    """"""

    def serialize(self, format="json", **export_kwargs):
        # dict(
        #     indent
        #     stream
        #     progress_output
        #     object_count
        # )

        (serializer_klass, renderer_klass) = self.model.get_default_serializer(
            format
        )

        if issubclass(serializer_klass, ModelSerializer) and renderer_klass:
            return serializer_klass(self, many=True).serialize_to_cli(
                renderer=renderer_klass, **export_kwargs
            )

        return serializer_klass().serialize(
            self,
            **dict(
                use_natural_foreign_keys=True,
                use_natural_primary_keys=True,
                **export_kwargs,
                # stream=stream or self.stdout,
                # progress_output=progress_output,
                # object_count=object_count,
            ),
        )


class NaturalKeyQuerySetMixin(object):
    """A mixin to add default natural-key behaviors to Civic QuerySets.

    Borrows somewhat heavily from the following project:
    https://github.com/wq/django-natural-keys/
    """

    def natural_key_kwargs(self, *args):
        """Turn args >> kwargs by merging with the natural key fields.

        Takes a list of args, which gets zipped together with the
        list generated by the model's get_natural_key_fields() method.

        Also checks to make sure the right number of args are submitted
        (otherwise Django doesn't enforce this, which can lead to only
        partial matches being evaluated and returned).
        """
        natural_key_fields = self.model.get_natural_key_fields()

        if len(args) != len(natural_key_fields):
            raise TypeError(
                "Mismatched number of args and natural-key fields: "
                f"expected {len(natural_key_fields)} argument(s)."
            )

        return dict(zip(natural_key_fields, args))


class BaseNaturalKeyQuerySet(NaturalKeyQuerySetMixin, CivicBaseQuerySet):
    pass
