"""
Regression tests for Model inheritance behavior.
"""
from __future__ import unicode_literals

import datetime
from operator import attrgetter
from unittest import expectedFailure

from django import forms
from django.test import TestCase

from .models import (
    ArticleWithAuthor, BachelorParty, BirthdayParty, BusStation, Child,
    DerivedM, InternalCertificationAudit, ItalianRestaurant, M2MChild,
    MessyBachelorParty, ParkingLot, ParkingLot3, ParkingLot4A, ParkingLot4B,
    Person, Place, Profile, QualityControl, Restaurant, SelfRefChild,
    SelfRefParent, Senator, Supplier, TrainStation, User, Wholesaler,
)


class ModelInheritanceTest(TestCase):
    def test_model_inheritance(self):
        # Regression for #7350, #7202
        # Check that when you create a Parent object with a specific reference
        # to an existent child instance, saving the Parent doesn't duplicate
        # the child. This behavior is only activated during a raw save - it
        # is mostly relevant to deserialization, but any sort of CORBA style
        # 'narrow()' API would require a similar approach.

        # Create a child-parent-grandparent chain
        place1 = Place(
            name="Guido's House of Pasta",
            address='944 W. Fullerton')
        place1.save_base(raw=True)
        restaurant = Restaurant(
            place_ptr=place1,
            serves_hot_dogs=True,
            serves_pizza=False)
        restaurant.save_base(raw=True)
        italian_restaurant = ItalianRestaurant(
            restaurant_ptr=restaurant,
            serves_gnocchi=True)
        italian_restaurant.save_base(raw=True)

        # Create a child-parent chain with an explicit parent link
        place2 = Place(name='Main St', address='111 Main St')
        place2.save_base(raw=True)
        park = ParkingLot(parent=place2, capacity=100)
        park.save_base(raw=True)

        # Check that no extra parent objects have been created.
        places = list(Place.objects.all())
        self.assertEqual(places, [place1, place2])

        dicts = list(Restaurant.objects.values('name', 'serves_hot_dogs'))
        self.assertEqual(dicts, [{
            'name': "Guido's House of Pasta",
            'serves_hot_dogs': True
        }])

        dicts = list(ItalianRestaurant.objects.values(
            'name', 'serves_hot_dogs', 'serves_gnocchi'))
        self.assertEqual(dicts, [{
            'name': "Guido's House of Pasta",
            'serves_gnocchi': True,
            'serves_hot_dogs': True,
        }])

        dicts = list(ParkingLot.objects.values('name', 'capacity'))
        self.assertEqual(dicts, [{
            'capacity': 100,
            'name': 'Main St',
        }])

        # You can also update objects when using a raw save.
        place1.name = "Guido's All New House of Pasta"
        place1.save_base(raw=True)

        restaurant.serves_hot_dogs = False
        restaurant.save_base(raw=True)

        italian_restaurant.serves_gnocchi = False
        italian_restaurant.save_base(raw=True)

        place2.name = 'Derelict lot'
        place2.save_base(raw=True)

        park.capacity = 50
        park.save_base(raw=True)

        # No extra parent objects after an update, either.
        places = list(Place.objects.all())
        self.assertEqual(places, [place2, place1])
        self.assertEqual(places[0].name, 'Derelict lot')
        self.assertEqual(places[1].name, "Guido's All New House of Pasta")

        dicts = list(Restaurant.objects.values('name', 'serves_hot_dogs'))
        self.assertEqual(dicts, [{
            'name': "Guido's All New House of Pasta",
            'serves_hot_dogs': False,
        }])

        dicts = list(ItalianRestaurant.objects.values(
            'name', 'serves_hot_dogs', 'serves_gnocchi'))
        self.assertEqual(dicts, [{
            'name': "Guido's All New House of Pasta",
            'serves_gnocchi': False,
            'serves_hot_dogs': False,
        }])

        dicts = list(ParkingLot.objects.values('name', 'capacity'))
        self.assertEqual(dicts, [{
            'capacity': 50,
            'name': 'Derelict lot',
        }])

        # If you try to raw_save a parent attribute onto a child object,
        # the attribute will be ignored.

        italian_restaurant.name = "Lorenzo's Pasta Hut"
        italian_restaurant.save_base(raw=True)

        # Note that the name has not changed
        # - name is an attribute of Place, not ItalianRestaurant
        dicts = list(ItalianRestaurant.objects.values(
            'name', 'serves_hot_dogs', 'serves_gnocchi'))
        self.assertEqual(dicts, [{
            'name': "Guido's All New House of Pasta",
            'serves_gnocchi': False,
            'serves_hot_dogs': False,
        }])

    def test_issue_7105(self):
        # Regressions tests for #7105: dates() queries should be able to use
        # fields from the parent model as easily as the child.
        Child.objects.create(
            name='child',
            created=datetime.datetime(2008, 6, 26, 17, 0, 0))
        datetimes = list(Child.objects.datetimes('created', 'month'))
        self.assertEqual(datetimes, [datetime.datetime(2008, 6, 1, 0, 0)])

    def test_issue_7276(self):
        # Regression test for #7276: calling delete() on a model with
        # multi-table inheritance should delete the associated rows from any
        # ancestor tables, as well as any descendent objects.
        place1 = Place(
            name="Guido's House of Pasta",
            address='944 W. Fullerton')
        place1.save_base(raw=True)
        restaurant = Restaurant(
            place_ptr=place1,
            serves_hot_dogs=True,
            serves_pizza=False)
        restaurant.save_base(raw=True)
        italian_restaurant = ItalianRestaurant(
            restaurant_ptr=restaurant,
            serves_gnocchi=True)
        italian_restaurant.save_base(raw=True)

        ident = ItalianRestaurant.objects.all()[0].id
        self.assertEqual(Place.objects.get(pk=ident), place1)
        Restaurant.objects.create(
            name='a',
            address='xx',
            serves_hot_dogs=True,
            serves_pizza=False)

        # This should delete both Restaurants, plus the related places, plus
        # the ItalianRestaurant.
        Restaurant.objects.all().delete()

        with self.assertRaises(Place.DoesNotExist):
            Place.objects.get(pk=ident)
        with self.assertRaises(ItalianRestaurant.DoesNotExist):
            ItalianRestaurant.objects.get(pk=ident)

    def test_issue_6755(self):
        """
        Regression test for #6755
        """
        r = Restaurant(serves_pizza=False, serves_hot_dogs=False)
        r.save()
        self.assertEqual(r.id, r.place_ptr_id)
        orig_id = r.id
        r = Restaurant(place_ptr_id=orig_id, serves_pizza=True, serves_hot_dogs=False)
        r.save()
        self.assertEqual(r.id, orig_id)
        self.assertEqual(r.id, r.place_ptr_id)

    def test_issue_7488(self):
        # Regression test for #7488. This looks a little crazy, but it's the
        # equivalent of what the admin interface has to do for the edit-inline
        # case.
        suppliers = Supplier.objects.filter(
            restaurant=Restaurant(name='xx', address='yy'))
        suppliers = list(suppliers)
        self.assertEqual(suppliers, [])