# Generated by Django 3.1.6 on 2021-06-04 16:46
import uuid
from django.db import migrations, models, transaction
import django.db.models.deletion
from django.db import IntegrityError
from django.db.models import F


def migrate_admin_user_to_system_user(apps, schema_editor):
    admin_user_model = apps.get_model("assets", "AdminUser")
    system_user_model = apps.get_model("assets", "SystemUser")
    db_alias = schema_editor.connection.alias

    admin_users = admin_user_model.objects.using(db_alias).all()
    print()
    for admin_user in admin_users:
        kwargs = {}
        for attr in [
            'org_id', 'username', 'password', 'private_key', 'public_key',
            'comment', 'date_created', 'date_updated', 'created_by',
        ]:
            value = getattr(admin_user, attr)
            kwargs[attr] = value

        name = admin_user.name
        exist = system_user_model.objects.using(db_alias).filter(
            name=admin_user.name, org_id=admin_user.org_id
        ).exists()
        if exist:
            name = admin_user.name + '_' + str(admin_user.id)[:5]

        i = admin_user.id
        exist = system_user_model.objects.using(db_alias).filter(
            id=i, org_id=admin_user.org_id
        ).exists()
        if exist:
            i = uuid.uuid4()

        kwargs.update({
            'id': i,
            'name': name,
            'type': 'admin',
            'protocol': 'ssh',
            'auto_push': False,
        })

        with transaction.atomic():
            s = system_user_model(**kwargs)
            try:
                s.save()
            except IntegrityError:
                s.id = None
                s.save()
            print("  Migrate admin user to system user: {} => {}".format(admin_user.name, s.name))
            assets = admin_user.assets.all()
            s.assets.set(assets)


def migrate_assets_admin_user(apps, schema_editor):
    asset_model = apps.get_model("assets", "Asset")
    db_alias = schema_editor.connection.alias
    assets = asset_model.objects.using(db_alias).all()
    assets.update(admin_user=F('_admin_user'))


class Migration(migrations.Migration):

    dependencies = [
        ('assets', '0070_auto_20210426_1515'),
    ]

    operations = [
        migrations.AddField(
            model_name='systemuser',
            name='type',
            field=models.CharField(choices=[('common', 'Common user'), ('admin', 'Admin user')], default='common', max_length=16, verbose_name='Type'),
        ),
        migrations.AlterField(
            model_name='systemuser',
            name='login_mode',
            field=models.CharField(choices=[('auto', 'Automatic managed'), ('manual', 'Manually input')], default='auto', max_length=10, verbose_name='Login mode'),
        ),
        migrations.AlterField(
            model_name='systemuser',
            name='protocol',
            field=models.CharField(choices=[('ssh', 'SSH'), ('rdp', 'RDP'), ('telnet', 'Telnet'), ('vnc', 'VNC'), ('mysql', 'MySQL'), ('oracle', 'Oracle'), ('mariadb', 'MariaDB'), ('postgresql', 'PostgreSQL'), ('k8s', 'K8S')], default='ssh', max_length=16, verbose_name='Protocol'),
        ),
        migrations.RunPython(migrate_admin_user_to_system_user),
        migrations.RenameField(
            model_name='asset',
            old_name='admin_user',
            new_name='_admin_user',
        ),
        migrations.AddField(
            model_name='asset',
            name='admin_user',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='admin_assets', to='assets.systemuser', verbose_name='Admin user'),
        ),
        migrations.RunPython(migrate_assets_admin_user),
        migrations.RemoveField(
            model_name='asset',
            name='_admin_user',
        ),
    ]
