# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-12 08:00
from __future__ import unicode_literals

from django.db import (IntegrityError, ProgrammingError, OperationalError,
                       connection, migrations, models, transaction)


def move_users(apps, schema_editor):
    if hasattr(schema_editor.connection.Database, 'sqlite_version'):
        # мы в тесте, тут нет старых таблиц
        return
    MyUser = apps.get_model("registration", "MyUser")
    try:
        class OldUser(models.Model):
            email = models.CharField(max_length=256)
            username = models.CharField(max_length=256)
            password = models.CharField()
            date_joined = models.DateTimeField()
            last_login = models.DateTimeField()
            is_superuser = models.BooleanField()
            is_staff = models.BooleanField()
            is_active = models.BooleanField()

            class Meta:
                db_table = 'auth_user'

        for old_user in OldUser.objects.all():
            try:
                with transaction.atomic():
                    MyUser.objects.create(
                        email=old_user.email,
                        password=old_user.password,
                        date_joined=old_user.date_joined,
                        name=old_user.username,
                        is_active=old_user.is_active,
                        is_admin=old_user.is_staff,
                        is_superuser=old_user.is_superuser
                    )
            except IntegrityError:
                print('Duplicate user email {}. Skipped.'.format(old_user.email))

        with connection.cursor() as cursor:
            cursor.execute('''
                ALTER TABLE intopython_db.django_admin_log
                ADD CONSTRAINT django_admin_log_registration_myuser_FK
                FOREIGN KEY (user_id) REFERENCES intopython_db.registration_myuser(id)''')
            cursor.execute('''
                ALTER TABLE intopython_db.django_admin_log
                DROP FOREIGN KEY django_admin_log_user_id_c564eba6_fk_auth_user_id''')
            cursor.execute('''DROP TABLE intopython_db.auth_user_groups''')
            cursor.execute('''DROP TABLE intopython_db.auth_user_user_permissions''')
            cursor.execute('''DROP TABLE intopython_db.auth_user''')
    except (ProgrammingError, OperationalError):
        # нет старых таблиц - пропускаем
        pass


def delete_users(apps, schema_editor):
    MyUser = apps.get_model("registration", "MyUser")
    with transaction.atomic():
        MyUser.objects.all().delete()


class Migration(migrations.Migration):

    dependencies = [
        ('registration', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(move_users, delete_users),
    ]
