# Generated by Django 3.2.6 on 2022-02-17 05:56

from django.db import migrations
from django.db.models import Max

from m3_gar.importer.commands import get_table_names


def mark_version_as_processed_by_status_table(apps, schema_editor):
    Status = apps.get_model('m3_gar', 'Status')
    Version = apps.get_model('m3_gar', 'Version')

    max_version = Status.objects.aggregate(Max('ver'))['ver__max']
    Version.objects.filter(ver__lte=max_version).update(processed=True)


def set_status_info_by_processed_version(apps, schema_editor):
    Status = apps.get_model('m3_gar', 'Status')
    Version = apps.get_model('m3_gar', 'Version')
    max_version = Version.objects.filter(processed=True).order_by('ver').last()

    if max_version:
        for table in get_table_names(None):
            status = Status(table=table, ver=max_version)
            status.save()


class Migration(migrations.Migration):

    dependencies = [
        ('m3_gar', '0007_version_processed'),
    ]

    operations = [
        migrations.RunPython(mark_version_as_processed_by_status_table, set_status_info_by_processed_version),
    ]
