from django.db import migrations


def update_content_types(apps, schema_editor):
    ContentType = apps.get_model('contenttypes', 'ContentType')
    db_alias = schema_editor.connection.alias

    # Delete the new ContentTypes effected by the new model in the core app
    ContentType.objects.using(db_alias).filter(app_label='core', model='objectchange').delete()

    # Update the app labels of the original ContentTypes for extras.ObjectChange to ensure that any
    # foreign key references are preserved
    ContentType.objects.using(db_alias).filter(app_label='extras', model='objectchange').update(app_label='core')


def update_dashboard_widgets(apps, schema_editor):
    Dashboard = apps.get_model('extras', 'Dashboard')
    db_alias = schema_editor.connection.alias

    for dashboard in Dashboard.objects.using(db_alias).all():
        for key, widget in dashboard.config.items():
            if widget['config'].get('model') == 'extras.objectchange':
                widget['config']['model'] = 'core.objectchange'
            elif models := widget['config'].get('models'):
                models = list(map(lambda x: x.replace('extras.objectchange', 'core.objectchange'), models))
                dashboard.config[key]['config']['models'] = models
        dashboard.save()


class Migration(migrations.Migration):
    dependencies = [
        ('extras', '0116_custom_link_button_color'),
        ('core', '0011_move_objectchange'),
    ]

    operations = [
        migrations.SeparateDatabaseAndState(
            state_operations=[
                migrations.DeleteModel(
                    name='ObjectChange',
                ),
            ],
            database_operations=[
                migrations.AlterModelTable(
                    name='ObjectChange',
                    table='core_objectchange',
                ),
                # Rename PK sequence
                migrations.RunSQL('ALTER TABLE extras_objectchange_id_seq' '  RENAME TO core_objectchange_id_seq'),
                # Rename indexes. Hashes generated by schema_editor._create_index_name()
                migrations.RunSQL('ALTER INDEX extras_objectchange_pkey' '  RENAME TO core_objectchange_pkey'),
                migrations.RunSQL(
                    'ALTER INDEX extras_obje_changed_927fe5_idx'
                    '  RENAME TO core_objectchange_changed_object_type_id_cha_79a9ed1e'
                ),
                migrations.RunSQL(
                    'ALTER INDEX extras_obje_related_bfcdef_idx'
                    '  RENAME TO core_objectchange_related_object_type_id_rel_a71d604a'
                ),
                migrations.RunSQL(
                    'ALTER INDEX extras_objectchange_changed_object_type_id_b755bb60'
                    '  RENAME TO core_objectchange_changed_object_type_id_2070ade6'
                ),
                migrations.RunSQL(
                    'ALTER INDEX extras_objectchange_related_object_type_id_fe6e521f'
                    '  RENAME TO core_objectchange_related_object_type_id_b80958af'
                ),
                migrations.RunSQL(
                    'ALTER INDEX extras_objectchange_request_id_4ae21e90'
                    '  RENAME TO core_objectchange_request_id_d9d160ac'
                ),
                migrations.RunSQL(
                    'ALTER INDEX extras_objectchange_time_224380ea' '  RENAME TO core_objectchange_time_800f60a5'
                ),
                migrations.RunSQL(
                    'ALTER INDEX extras_objectchange_user_id_7fdf8186' '  RENAME TO core_objectchange_user_id_2b2142be'
                ),
                # Rename constraints
                migrations.RunSQL(
                    'ALTER TABLE core_objectchange RENAME CONSTRAINT '
                    'extras_objectchange_changed_object_id_check TO '
                    'core_objectchange_changed_object_id_check'
                ),
                migrations.RunSQL(
                    'ALTER TABLE core_objectchange RENAME CONSTRAINT '
                    'extras_objectchange_related_object_id_check TO '
                    'core_objectchange_related_object_id_check'
                ),
                migrations.RunSQL(
                    'ALTER TABLE core_objectchange RENAME CONSTRAINT '
                    'extras_objectchange_changed_object_type__b755bb60_fk_django_co TO '
                    'core_objectchange_changed_object_type_id_2070ade6'
                ),
                migrations.RunSQL(
                    'ALTER TABLE core_objectchange RENAME CONSTRAINT '
                    'extras_objectchange_related_object_type__fe6e521f_fk_django_co TO '
                    'core_objectchange_related_object_type_id_b80958af'
                ),
                migrations.RunSQL(
                    'ALTER TABLE core_objectchange RENAME CONSTRAINT '
                    'extras_objectchange_user_id_7fdf8186_fk_auth_user_id TO '
                    'core_objectchange_user_id_2b2142be'
                ),
            ],
        ),
        migrations.RunPython(code=update_content_types, reverse_code=migrations.RunPython.noop),
        migrations.RunPython(code=update_dashboard_widgets, reverse_code=migrations.RunPython.noop),
    ]
