# coding=utf-8

from django.core.management import BaseCommand
from django.db.models.fields.related import ForeignRelatedObjectsDescriptor, ManyRelatedObjectsDescriptor, \
    SingleRelatedObjectDescriptor

from api.models import City, Province


class Command(BaseCommand):
    def handle(self, *args, **options):
        reverse_refs = []
        for k, v in City.__dict__.iteritems():
            if isinstance(v, (SingleRelatedObjectDescriptor,
                              ForeignRelatedObjectsDescriptor,
                              ManyRelatedObjectsDescriptor)):
                reverse_refs.append((k, v))

        invalid_cities = City.objects.filter(id__in=['xinsu', 'segu'])

        default = City.objects.get(id='dongjing')
        for city in invalid_cities:
            for ref_name, ref_obj in reverse_refs:
                if isinstance(ref_obj, SingleRelatedObjectDescriptor):
                    try:
                        obj = getattr(city, ref_name)
                        print(u"Related name: {}, correspond id: {}, correspond city_id: {}, city id: {}.".format(
                            ref_name, obj.id, obj.city_id, city.id))

                        while True:
                            op = raw_input('是否删除数据(y/n)\n').strip()
                            if op and op in 'yn':
                                break
                        if op == 'y':
                            obj.city = default
                            obj.save(update_fields=['city'])
                            print(u'修改成功')
                    except Exception:
                        pass
                elif isinstance(ref_obj, ForeignRelatedObjectsDescriptor):
                    for obj in getattr(city, ref_name).all():
                        print(u"Related name: {}, correspond id: {}, correspond city_id: {}, city id: {}.".format(
                            ref_name, obj.id, obj.city_id, city.id))

                        while True:
                            op = raw_input('是否删除数据(y/n)\n').strip()
                            if op and op in 'yn':
                                break
                        if op == 'y':
                            obj.city = default
                            obj.save(update_fields=['city'])
                            print(u'修改成功')

        invalid_cities.delete()

        print('Clear up done.')
