"""
The `ModelSerializer` and `HyperlinkedModelSerializer` classes are essentially
shortcuts for automatically creating serializers based on a given model class.

These tests deal with ensuring that we correctly map the model fields onto
an appropriate set of serializer fields for each case.
"""
from __future__ import unicode_literals

import decimal
from collections import OrderedDict

from django.core.exceptions import ImproperlyConfigured
from django.core.validators import (
    MaxValueValidator, MinLengthValidator, MinValueValidator
)
from django.db import models
from django.db.models import DurationField as ModelDurationField
from django.test import TestCase
from django.utils import six

from rest_framework import serializers
from rest_framework.compat import unicode_repr


def dedent(blocktext):
    return '\n'.join([line[12:] for line in blocktext.splitlines()[1:-1]])


# Tests for regular field mappings.
# ---------------------------------

class CustomField(models.Field):
    """
    A custom model field simply for testing purposes.
    """
    pass


class OneFieldModel(models.Model):
    char_field = models.CharField(max_length=100)


class RegularFieldsModel(models.Model):
    """
    A model class for testing regular flat fields.
    """
    auto_field = models.AutoField(primary_key=True)
    big_integer_field = models.BigIntegerField()
    boolean_field = models.BooleanField(default=False)
    char_field = models.CharField(max_length=100)
    comma_separated_integer_field = models.CommaSeparatedIntegerField(max_length=100)
    date_field = models.DateField()
    datetime_field = models.DateTimeField()
    decimal_field = models.DecimalField(max_digits=3, decimal_places=1)
    email_field = models.EmailField(max_length=100)
    float_field = models.FloatField()
    integer_field = models.IntegerField()
    null_boolean_field = models.NullBooleanField()
    positive_integer_field = models.PositiveIntegerField()
    positive_small_integer_field = models.PositiveSmallIntegerField()
    slug_field = models.SlugField(max_length=100)
    small_integer_field = models.SmallIntegerField()
    text_field = models.TextField(max_length=100)
    time_field = models.TimeField()
    url_field = models.URLField(max_length=100)
    custom_field = CustomField()
    file_path_field = models.FilePathField(path='/tmp/')

    def method(self):
        return 'method'


COLOR_CHOICES = (('red', 'Red'), ('blue', 'Blue'), ('green', 'Green'))
DECIMAL_CHOICES = (('low', decimal.Decimal('0.1')), ('medium', decimal.Decimal('0.5')), ('high', decimal.Decimal('0.9')))


class FieldOptionsModel(models.Model):
    value_limit_field = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)])
    length_limit_field = models.CharField(validators=[MinLengthValidator(3)], max_length=12)
    blank_field = models.CharField(blank=True, max_length=10)
    null_field = models.IntegerField(null=True)
    default_field = models.IntegerField(default=0)
    descriptive_field = models.IntegerField(help_text='Some help text', verbose_name='A label')
    choices_field = models.CharField(max_length=100, choices=COLOR_CHOICES)


class ChoicesModel(models.Model):
    choices_field_with_nonstandard_args = models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES, verbose_name='A label')


class TestModelSerializer(TestCase):
    def test_create_method(self):
        class TestSerializer(serializers.ModelSerializer):
            non_model_field = serializers.CharField()

            class Meta:
                model = OneFieldModel
                fields = ('char_field', 'non_model_field')

        serializer = TestSerializer(data={
            'char_field': 'foo',
            'non_model_field': 'bar',
        })
        serializer.is_valid()
        with self.assertRaises(TypeError) as excinfo:
            serializer.save()
        msginitial = 'Got a `TypeError` when calling `OneFieldModel.objects.create()`.'
        assert str(excinfo.exception).startswith(msginitial)

    def test_abstract_model(self):
        """
        Test that trying to use ModelSerializer with Abstract Models
        throws a ValueError exception.
        """
        class AbstractModel(models.Model):
            afield = models.CharField(max_length=255)

            class Meta:
                abstract = True

        class TestSerializer(serializers.ModelSerializer):
            class Meta:
                model = AbstractModel
                fields = ('afield',)

        serializer = TestSerializer(data={
            'afield': 'foo',
        })
        with self.assertRaises(ValueError) as excinfo:
            serializer.is_valid()
        msginitial = 'Cannot use ModelSerializer with Abstract Models.'
        assert str(excinfo.exception).startswith(msginitial)


class TestRegularFieldMappings(TestCase):
    def test_regular_fields(self):
        """
        Model fields should map to their equivalent serializer fields.
        """
        class TestSerializer(serializers.ModelSerializer):
            class Meta:
                model = RegularFieldsModel
                fields = '__all__'

        expected = dedent("""
            TestSerializer():
                auto_field = IntegerField(read_only=True)
                big_integer_field = IntegerField()
                boolean_field = BooleanField(required=False)
                char_field = CharField(max_length=100)
                comma_separated_integer_field = CharField(max_length=100, validators=[<django.core.validators.RegexValidator object>])
                date_field = DateField()
                datetime_field = DateTimeField()
                decimal_field = DecimalField(decimal_places=1, max_digits=3)
                email_field = EmailField(max_length=100)
                float_field = FloatField()
                integer_field = IntegerField()
                null_boolean_field = NullBooleanField(required=False)
                positive_integer_field = IntegerField()
                positive_small_integer_field = IntegerField()
                slug_field = SlugField(max_length=100)
                small_integer_field = IntegerField()
                text_field = CharField(max_length=100, style={'base_template': 'textarea.html'})
                time_field = TimeField()
                url_field = URLField(max_length=100)
                custom_field = ModelField(model_field=<tests.test_model_serializer.CustomField: custom_field>)
                file_path_field = FilePathField(path='/tmp/')
        """)

        self.assertEqual(unicode_repr(TestSerializer()), expected)

    def test_field_options(self):
        class TestSerializer(serializers.ModelSerializer):
            class Meta:
                model = FieldOptionsModel
                fields = '__all__'

        expected = dedent("""
            TestSerializer():
                id = IntegerField(label='ID', read_only=True)
                value_limit_field = IntegerField(max_value=10, min_value=1)
                length_limit_field = CharField(max_length=12, min_length=3)
                blank_field = CharField(allow_blank=True, max_length=10, required=False)
                null_field = IntegerField(allow_null=True, required=False)
                default_field = IntegerField(required=False)
                descriptive_field = IntegerField(help_text='Some help text', label='A label')
                choices_field = ChoiceField(choices=(('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')))
        """)
        if six.PY2:
            # This particular case is too awkward to resolve fully across
            # both py2 and py3.
            expected = expected.replace(
                "('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')",
                "(u'red', u'Red'), (u'blue', u'Blue'), (u'green', u'Green')"
            )
        self.assertEqual(unicode_repr(TestSerializer()), expected)

    def test_method_field(self):
        """
        Properties and methods on the model should be allowed as `Meta.fields`
        values, and should map to `ReadOnlyField`.
        """
        class TestSerializer(serializers.ModelSerializer):
            class Meta:
                model = RegularFieldsModel
                fields = ('auto_field', 'method')

        expected = dedent("""
            TestSerializer():
                auto_field = IntegerField(read_only=True)
                method = ReadOnlyField()
        """)
        self.assertEqual(repr(TestSerializer()), expected)

    def test_pk_fields(self):
        """
        Both `pk` and the actual primary key name are valid in `Meta.fields`.
        """
        class TestSerializer(serializers.ModelSerializer):
            class Meta:
                model = RegularFieldsModel
                fields = ('pk', 'auto_field')

        expected = dedent("""
            TestSerializer():
                pk = IntegerField(label='Auto field', read_only=True)
                auto_field = IntegerField(read_only=True)
        """)
        self.assertEqual(repr(TestSerializer()), expected)

    def test_extra_field_kwargs(self):
        """
        Ensure `extra_kwargs` are passed to generated fields.
        """
        class TestSerializer(serializers.ModelSerializer):
            class Meta:
                model = RegularFieldsModel
                fields = ('auto_field', 'char_field')
                extra_kwargs = {'char_field': {'default': 'extra'}}

        expected = dedent("""
            TestSerializer():
                auto_field = IntegerField(read_only=True)
                char_field = CharField(default='extra', max_length=100)
        """)
        self.assertEqual(repr(TestSerializer()), expected)

    def test_extra_field_kwargs_required(self):
        """
        Ensure `extra_kwargs` are passed to generated fields.
        """
        class TestSerializer(serializers.ModelSerializer):
            class Meta:
                model = RegularFieldsModel
                fields = ('auto_field', 'char_field')
                extra_kwargs = {'auto_field': {'required': False, 'read_only': False}}

        expected = dedent("""
            TestSerializer():
                auto_field = IntegerField(read_only=False, required=False)
                char_field = CharField(max_length=100)
        """)
        self.assertEqual(repr(TestSerializer()), expected)

    def test_invalid_field(self):
        """
        Field names that do not map to a model field or relationship should
        raise a configuration errror.
        """
        class TestSerializer(serializers.ModelSerializer):
            class Meta:
                model = RegularFieldsModel
                fields = ('auto_field', 'invalid')

        with self.assertRaises(ImproperlyConfigured) as excinfo:
            TestSerializer().fields
        expected = 'Field name `invalid` is not valid for model `RegularFieldsModel`.'
        assert str(excinfo.exception) == expected

    def test_missing_field(self):
        """
        Fields that have been declared on the serializer class must be included
        in the `Meta.fields` if it exists.
        """
        class TestSerializer(serializers.ModelSerializer):
            missing = serializers.ReadOnlyField()

            class Meta:
                model = RegularFieldsModel
                fields = ('auto_field',)

        with self.assertRaises(AssertionError) as excinfo:
            TestSerializer().fields
        expected = (
            "The field 'missing' was declared on serializer TestSerializer, "
            "but has not been included in the 'fields' option."
        )
        assert str(excinfo.exception) == expected

    def test_missing_superclass_field(self):
        """
        Fields that have been declared on a parent of the serializer class may
        be excluded from the `Meta.fields` option.
        """
        class TestSerializer(serializers.ModelSerializer):
            missing = serializers.ReadOnlyField()

            class Meta:
                model = RegularFieldsModel
                fields = '__all__'

        class ChildSerializer(TestSerializer):
            missing = serializers.ReadOnlyField()

            class Meta:
                model = RegularFieldsModel
                fields = ('auto_field',)

        ChildSerializer().fields

    def test_choices_with_nonstandard_args(self):
        class ExampleSerializer(serializers.ModelSerializer):
            class Meta:
                model = ChoicesModel
                fields = '__all__'

        ExampleSerializer()

    def test_fields_and_exclude_behavior(self):
        class ImplicitFieldsSerializer(serializers.ModelSerializer):
            class Meta:
                model = RegularFieldsModel
                fields = '__all__'

        class ExplicitFieldsSerializer(serializers.ModelSerializer):
            class Meta:
                model = RegularFieldsModel
                fields = '__all__'

        implicit = ImplicitFieldsSerializer()
        explicit = ExplicitFieldsSerializer()

        assert implicit.data == explicit.data


class TestDurationFieldMapping(TestCase):
    def test_duration_field(self):