# Generated by Django 4.1.9 on 2023-09-05 14:14

from django.db import migrations


def migrate_external_ids(apps, schema_editor):
    Book = apps.get_model('documents', 'Book')
    Site = apps.get_model('depot', 'Site')
    SiteBook = apps.get_model('depot', 'SiteBook')
    SiteBookPublish = apps.get_model('depot', 'SiteBookPublish')

    site_types = ('legimi', 'woblink')
    for site_type in site_types:
        site = Site.objects.filter(site_type=site_type).first()
        if site is None:
            continue
        for book in Book.objects.exclude(**{f'{site_type}_id': ''}):
            SiteBook.objects.get_or_create(
                site=site, book=book,
                external_id=getattr(book, f'{site_type}_id')
            )

    for p in SiteBookPublish.objects.all():
        p.site_book, created = SiteBook.objects.get_or_create(
            site=p.site,
            book=p.book
        )
        p.save(update_fields=['site_book'])
            
    

def remigrate_external_ids(apps, schema_editor):
    Book = apps.get_model('documents', 'Book')
    Site = apps.get_model('depot', 'Site')
    SiteBook = apps.get_model('depot', 'SiteBook')
    SiteBookPublish = apps.get_model('depot', 'SiteBookPublish')

    for p in SiteBookPublish.objects.exclude(site_book=None):
        p.site = p.site_book.site
        p.book = p.site_book.book
        p.save(update_fields=['site', 'book'])

    site_types = ('legimi', 'woblink')
    for site_type in site_types:
        for site_book in SiteBook.objects.exclude(external_id=None):
            book = site_book.book
            setattr(book, f'{site_type}_id', site_book.external_id)
            book.save(update_fields=[f'{site_type}_id'])
    

class Migration(migrations.Migration):

    dependencies = [
        ("depot", "0009_sitebook_sitebookpublish_site_book"),
    ]

    operations = [
        migrations.RunPython(
            migrate_external_ids,
            remigrate_external_ids,
        )
    ]
