# Generated by Django 3.2.18 on 2023-08-03 08:32

from django.db import migrations, models
import django.db.models.deletion
from django.core.exceptions import ObjectDoesNotExist


def migrate_bookmark(apps, schema_editor):
    BookMark = apps.get_model("judge", "BookMark")
    Problem = apps.get_model("judge", "Problem")
    Solution = apps.get_model("judge", "Solution")
    BlogPost = apps.get_model("judge", "BlogPost")
    Contest = apps.get_model("judge", "Contest")

    for bookmark in BookMark.objects.all():
        page = bookmark.page
        try:
            if page.startswith("p:"):
                code = page[2:]
                bookmark.linked_object = Problem.objects.get(code=code)
            elif page.startswith("s:"):
                code = page[2:]
                bookmark.linked_object = Solution.objects.get(problem__code=code)
            elif page.startswith("c:"):
                key = page[2:]
                bookmark.linked_object = Contest.objects.get(key=key)
            elif page.startswith("b:"):
                blog_id = page[2:]
                bookmark.linked_object = BlogPost.objects.get(id=blog_id)
            bookmark.save()
        except ObjectDoesNotExist:
            bookmark.delete()


class Migration(migrations.Migration):

    dependencies = [
        ("contenttypes", "0002_remove_content_type_name"),
        ("judge", "0159_auto_20230803_1518"),
    ]

    operations = [
        migrations.AddField(
            model_name="bookmark",
            name="content_type",
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to="contenttypes.contenttype",
            ),
        ),
        migrations.AddField(
            model_name="bookmark",
            name="object_id",
            field=models.PositiveIntegerField(default=1),
        ),
        migrations.AddField(
            model_name="bookmark",
            name="score",
            field=models.IntegerField(default=0, verbose_name="votes"),
        ),
        migrations.AlterUniqueTogether(
            name="bookmark",
            unique_together={("content_type", "object_id")},
        ),
        migrations.AddIndex(
            model_name="bookmark",
            index=models.Index(
                fields=["content_type", "object_id"],
                name="judge_bookm_content_964329_idx",
            ),
        ),
        migrations.AddIndex(
            model_name="makebookmark",
            index=models.Index(
                fields=["user", "bookmark"], name="judge_makeb_user_id_f0e226_idx"
            ),
        ),
        migrations.RunPython(migrate_bookmark, migrations.RunPython.noop, atomic=True),
    ]
