# Generated by Django 3.0.14 on 2021-11-19 20:13
from django.conf import settings
from django.contrib.admin.models import CHANGE
from django.db import migrations
from django.db.models import Value
from django.db.models.functions import Replace


def rename_pul_specialcollections(apps, schema_editor):
    Bibliography = apps.get_model("footnotes", "Bibliography")
    ContentType = apps.get_model("contenttypes", "ContentType")
    User = apps.get_model("auth", "User")
    LogEntry = apps.get_model("admin", "LogEntry")


    bibl_content_type = ContentType.objects.get(
        app_label="footnotes", model="bibliography",
    )
    script_user = User.objects.get(username=settings.SCRIPT_USERNAME)

    from_text = (
        "Department of Rare Books and Special Collections, Princeton University Library"
    )
    to_text = "Department of Special Collections, Princeton University Library"

    # identify records that need to be changed
    to_update = Bibliography.objects.filter(bibliographic_note__contains=from_text)
    # preserve as a list so queryset doesn't erase our set of records
    update_pks = list(to_update.values_list("pk", flat=True))
    # do a bulk update to replace the text
    to_update.update(
        bibliographic_note=Replace("bibliographic_note", Value(from_text), Value(to_text))
    )
    # get fresh copies of the updated records and create log entries
    for record in Bibliography.objects.filter(pk__in=update_pks):
        LogEntry.objects.create(
            user_id=script_user.id,
            content_type_id=bibl_content_type.pk,
            object_id=record.pk,
            object_repr=str(record),
            action_flag=CHANGE,
            change_message="Updated PUL Special Collections name in bibliographic note"
            )

class Migration(migrations.Migration):

    dependencies = [
        ("footnotes", "0006_alter_footnote_content_type"),
    ]

    operations = [
        migrations.RunPython(rename_pul_specialcollections,
                        migrations.RunPython.noop)

    ]
