# Generated by Django 3.2 on 2021-05-21 00:17

from django.db import migrations
import bookwyrm
from bookwyrm.connectors.abstract_connector import infer_physical_format


def infer_format(app_registry, schema_editor):
    """set the new phsyical format field based on existing format data"""
    db_alias = schema_editor.connection.alias

    editions = (
        app_registry.get_model("bookwyrm", "Edition")
        .objects.using(db_alias)
        .filter(physical_format_detail__isnull=False)
    )
    for edition in editions:
        free_format = edition.physical_format_detail.lower()
        edition.physical_format = infer_physical_format(free_format)
        edition.save()


def reverse(app_registry, schema_editor):
    """doesn't need to do anything"""


class Migration(migrations.Migration):

    dependencies = [
        ("bookwyrm", "0100_shelf_description"),
    ]

    operations = [
        migrations.RenameField(
            model_name="edition",
            old_name="physical_format",
            new_name="physical_format_detail",
        ),
        migrations.AddField(
            model_name="edition",
            name="physical_format",
            field=bookwyrm.models.fields.CharField(
                blank=True,
                choices=[
                    ("AudiobookFormat", "Audiobook"),
                    ("EBook", "eBook"),
                    ("GraphicNovel", "Graphic novel"),
                    ("Hardcover", "Hardcover"),
                    ("Paperback", "Paperback"),
                ],
                max_length=255,
                null=True,
            ),
        ),
        migrations.RunPython(infer_format, reverse),
    ]