# Generated by Django 2.2.13 on 2020-10-28 02:19

import common.utils.django
from django.conf import settings
from django.db import migrations, models
import django.utils.timezone
import uuid


def old_perm_to_application_permission_json(old_perm, category, _type):
    return {
        'id': old_perm.id,
        'name': old_perm.name,
        'category': category,
        'type': _type,
        'is_active': old_perm.is_active,
        'date_start': old_perm.date_start,
        'date_expired': old_perm.date_expired,
        'created_by': old_perm.created_by,
        'comment': old_perm.comment,
        'org_id': old_perm.org_id
    }


def common_old_perm_relation_to_application_permission_json(old_perm_relation, data_json):
    return {
        'applicationpermission_id': getattr(old_perm_relation, data_json['relation_app_perm_id']),
    }


def old_perm_relation_app_to_application_permission_json(old_perm_relation_app, data_json):
    data = common_old_perm_relation_to_application_permission_json(old_perm_relation_app, data_json)
    data.update({
        'application_id': getattr(old_perm_relation_app, data_json['relation_app_id'])
    })
    return data


def old_perm_relation_system_user_to_application_permission_json(old_perm_relation_system_user, data_json):
    data = common_old_perm_relation_to_application_permission_json(old_perm_relation_system_user, data_json)
    data.update({
        'systemuser_id': old_perm_relation_system_user.systemuser_id,
    })
    return data


def old_perm_relation_user_group_to_application_permission_json(old_perm_relation_user_group, data_json):
    data = common_old_perm_relation_to_application_permission_json(old_perm_relation_user_group, data_json)
    data.update({
        'usergroup_id': old_perm_relation_user_group.usergroup_id,
    })
    return data


def old_perm_relation_user_to_application_permission_json(old_perm_relation_user, data_json):
    data = common_old_perm_relation_to_application_permission_json(old_perm_relation_user, data_json)
    data.update({
        'user_id': old_perm_relation_user.user_id,
    })
    return data


CATEGORY_DB = 'db'
CATEGORY_REMOTE = 'remote_app'
CATEGORY_CLOUD = 'cloud'

TYPE_DB_MYSQL = 'mysql'
TYPE_CLOUD_K8S = 'k8s'
TYPE_REMOTE_CHROME = 'chrome'
TYPE_REMOTE_MYSQL_WORKBENCH = 'mysql_workbench'
TYPE_REMOTE_VMWARE_CLIENT = 'vmware_client'
TYPE_REMOTE_CUSTOM = 'custom'


OLD_PERM_MODELS_NAME_MAP_DATA_JSON = {
    'DatabaseAppPermission': {
        'app_m2m_fields': 'database_apps',
        'relation_app_perm_id': 'databaseapppermission_id',
        'relation_app_id': 'databaseapp_id',
        'category': CATEGORY_DB,
        'type': TYPE_DB_MYSQL,
    },
    'RemoteAppPermission': {
        'app_m2m_fields': 'remote_apps',
        'relation_app_perm_id': 'remoteapppermission_id',
        'relation_app_id': 'remoteapp_id',
        'category': CATEGORY_REMOTE,
        'type': None,
    },
    'K8sAppPermission': {
        'app_m2m_fields': 'k8s_apps',
        'relation_app_perm_id': 'k8sapppermission_id',
        'relation_app_id': 'k8sapp_id',
        'category': CATEGORY_CLOUD,
        'type': TYPE_CLOUD_K8S,
    }
}


def migrate_and_integrate_application_permissions(apps, schema_editor):
    db_alias = schema_editor.connection.alias

    new_app_perms_json = []
    new_app_perms_relation_apps_json = []
    new_app_perms_relation_system_users_json = []
    new_app_perms_relation_user_groups_json = []
    new_app_perms_relation_users_json = []

    for old_perm_model_name, data_json in OLD_PERM_MODELS_NAME_MAP_DATA_JSON.items():

        # model
        old_perm_model = apps.get_model("perms", old_perm_model_name)

        # instances
        old_perms = old_perm_model.objects.using(db_alias).all()
        old_perms_relation_apps = getattr(old_perm_model, data_json['app_m2m_fields']).through.objects.using(db_alias).all()
        old_perms_relation_system_users = old_perm_model.system_users.through.objects.using(db_alias).all()
        old_perms_relation_user_groups = old_perm_model.user_groups.through.objects.using(db_alias).all()
        old_perms_relation_users = old_perm_model.users.through.objects.using(db_alias).all()

        # json
        perms_json = []
        category = data_json['category']
        for old_perm in old_perms:
            if category == CATEGORY_REMOTE:
                type_list = list(old_perm.remote_apps.values_list('type', flat=True))
                if len(type_list) == 0:
                    _type = TYPE_REMOTE_CHROME
                else:
                    _type = max(type_list, key=type_list.count)
            else:
                _type = data_json['type']
            perm_json = old_perm_to_application_permission_json(old_perm, category, _type)
            perms_json.append(perm_json)

        perms_relation_apps_json = [
            old_perm_relation_app_to_application_permission_json(old_perm_relation_app, data_json)
            for old_perm_relation_app in old_perms_relation_apps
        ]
        perms_relation_system_users_json = [
            old_perm_relation_system_user_to_application_permission_json(old_perm_relation_system_user, data_json)
            for old_perm_relation_system_user in old_perms_relation_system_users
        ]
        perms_relation_user_groups_json = [
            old_perm_relation_user_group_to_application_permission_json(old_perm_relation_user_group, data_json)
            for old_perm_relation_user_group in old_perms_relation_user_groups
        ]
        perms_relation_users_json = [
            old_perm_relation_user_to_application_permission_json(old_perm_relation_user, data_json)
            for old_perm_relation_user in old_perms_relation_users
        ]

        new_app_perms_json.extend(perms_json)
        new_app_perms_relation_apps_json.extend(perms_relation_apps_json)
        new_app_perms_relation_system_users_json.extend(perms_relation_system_users_json)
        new_app_perms_relation_user_groups_json.extend(perms_relation_user_groups_json)
        new_app_perms_relation_users_json.extend(perms_relation_users_json)

    # model
    new_app_perm_model = apps.get_model("perms", "ApplicationPermission")
    new_app_perm_relation_app_model = new_app_perm_model.applications.through
    new_app_perm_relation_system_user_model = new_app_perm_model.system_users.through
    new_app_perm_relation_user_group_model = new_app_perm_model.user_groups.through
    new_app_perm_relation_user_model = new_app_perm_model.users.through

    # instances
    new_app_perm_objects = [
        new_app_perm_model(**data)
        for data in new_app_perms_json
    ]
    new_app_perm_relation_app_objects = [
        new_app_perm_relation_app_model(**data)
        for data in new_app_perms_relation_apps_json
    ]
    new_app_perm_relation_system_user_objects = [
        new_app_perm_relation_system_user_model(**data)
        for data in new_app_perms_relation_system_users_json
    ]
    new_app_perm_relation_user_group_objects = [
        new_app_perm_relation_user_group_model(**data)
        for data in new_app_perms_relation_user_groups_json
    ]
    new_app_perm_relation_user_objects = [
        new_app_perm_relation_user_model(**data)
        for data in new_app_perms_relation_users_json
    ]

    # create
    for new_app_perm_object in new_app_perm_objects:
        if new_app_perm_model.objects.using(db_alias).filter(name=new_app_perm_object.name).exists():
            new_app_perm_object.name = '{}-{}'.format(new_app_perm_object.name, str(new_app_perm_object.id)[:4])
        new_app_perm_object.save()
    new_app_perm_relation_app_model.objects.using(db_alias).bulk_create(new_app_perm_relation_app_objects)
    new_app_perm_relation_system_user_model.objects.using(db_alias).bulk_create(new_app_perm_relation_system_user_objects)
    new_app_perm_relation_user_group_model.objects.using(db_alias).bulk_create(new_app_perm_relation_user_group_objects)
    new_app_perm_relation_user_model.objects.using(db_alias).bulk_create(new_app_perm_relation_user_objects)



class Migration(migrations.Migration):

    dependencies = [
        ('users', '0030_auto_20200819_2041'),
        ('assets', '0059_auto_20201027_1905'),
        ('applications', '0006_application'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('perms', '0015_auto_20200929_1728'),
    ]

    operations = [
        migrations.CreateModel(
            name='ApplicationPermission',
            fields=[
                ('org_id', models.CharField(blank=True, db_index=True, default='', max_length=36, verbose_name='Organization')),
                ('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=128, verbose_name='Name')),
                ('is_active', models.BooleanField(default=True, verbose_name='Active')),
                ('date_start', models.DateTimeField(db_index=True, default=django.utils.timezone.now, verbose_name='Date start')),
                ('date_expired', models.DateTimeField(db_index=True, default=common.utils.django.date_expired_default, verbose_name='Date expired')),
                ('created_by', models.CharField(blank=True, max_length=128, verbose_name='Created by')),
                ('date_created', models.DateTimeField(auto_now_add=True, verbose_name='Date created')),
                ('comment', models.TextField(blank=True, verbose_name='Comment')),
                ('category', models.CharField(choices=[('db', 'Database'), ('remote_app', 'Remote app'), ('cloud', 'Cloud')], max_length=16, verbose_name='Category')),
                ('type', models.CharField(choices=[('mysql', 'MySQL'), ('oracle', 'Oracle'), ('postgresql', 'PostgreSQL'), ('mariadb', 'MariaDB'), ('chrome', 'Chrome'), ('mysql_workbench', 'MySQL Workbench'), ('vmware_client', 'vSphere Client'), ('custom', 'Custom'), ('k8s', 'Kubernetes')], max_length=16, verbose_name='Type')),
                ('applications', models.ManyToManyField(blank=True, related_name='granted_by_permissions', to='applications.Application', verbose_name='Application')),
                ('system_users', models.ManyToManyField(related_name='granted_by_application_permissions', to='assets.SystemUser', verbose_name='System user')),
                ('user_groups', models.ManyToManyField(blank=True, related_name='applicationpermissions', to='users.UserGroup', verbose_name='User group')),
                ('users', models.ManyToManyField(blank=True, related_name='applicationpermissions', to=settings.AUTH_USER_MODEL, verbose_name='User')),
            ],
            options={
                'verbose_name': 'Application permission',
                'ordering': ('name',),
                'unique_together': {('org_id', 'name')},
            },
        ),
        migrations.RunPython(migrate_and_integrate_application_permissions),
    ]