# Generated by Django 3.1.13 on 2021-10-21 18:27

from django.db import migrations
from django.conf import settings
from django.core.files.base import ContentFile

def forwards_func(apps, schema_editor):
    if not settings.IGNORE_MIGRATION:
        Observation = apps.get_model("base", "Observation")
        DemodData = apps.get_model("base", "DemodData")

        observations = Observation.objects.filter(payload='').exclude(payload_old='')
        for observation in observations:
            if observation.payload_old.storage.exists(observation.payload_old.name):
                audio_file = ContentFile(observation.payload_old.read())
                audio_file.name = observation.payload_old.name.split('/')[-1]
                observation.payload = audio_file
                observation.save()
                if observation.payload.storage.exists(observation.payload.name):
                   observation.payload_old.delete()

        observations = Observation.objects.filter(waterfall='').exclude(waterfall_old='')
        for observation in observations:
            if observation.waterfall_old.storage.exists(observation.waterfall_old.name):
                waterfall_file = ContentFile(observation.waterfall_old.read())
                waterfall_file.name = observation.waterfall_old.name.split('/')[-1]
                observation.waterfall = waterfall_file
                observation.save()
                if observation.waterfall.storage.exists(observation.waterfall.name):
                   observation.waterfall_old.delete()

        demoddata = DemodData.objects.filter(demodulated_data='').exclude(payload_demod='')
        for datum in demoddata:
            if datum.payload_demod.storage.exists(datum.payload_demod.name):
                data_file = ContentFile(datum.payload_demod.read())
                data_file.name = datum.payload_demod.name.split('/')[-1]
                datum.demodulated_data = data_file
                datum.save()
                if datum.demodulated_data.storage.exists(datum.demodulated_data.name):
                   datum.payload_demod.delete()

def reverse_func(apps, schema_editor):
    pass

class Migration(migrations.Migration):

    dependencies = [
        ('base', '0093_check_old_demoddata_if_are_images'),
    ]

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]
