# Generated by Django 2.2.5 on 2019-12-26 20:45

from django.db import migrations, models
import django.db.models.deletion

def non_reversible_migration(apps, schema_editor):
    """Operation to "reverse" an unreversible change"""
    pass

def remove_non_sadd_disaggregations(apps, schema_editor):
    DisaggregationType = apps.get_model('indicators', 'DisaggregationType')
    standard_disaggregations = DisaggregationType.objects.filter(standard=True, is_archived=False)
    for standard_disaggregation in standard_disaggregations:
        if standard_disaggregation.disaggregation_type == '---':
            standard_disaggregation.delete()
        elif standard_disaggregation.country_id == 6:
            standard_disaggregation.standard = False
            standard_disaggregation.save()
        elif standard_disaggregation.disaggregation_type == 'SADD - MC Standard':
            standard_disaggregation.disaggregation_type = 'Sex and Age Disaggregated Data (SADD)'
            standard_disaggregation.selected_by_default = True
            standard_disaggregation.save()

def assign_sadd_to_all_existing_indicators(apps, schema_editor):
    Indicator = apps.get_model('indicators', 'Indicator')
    DisaggregationType = apps.get_model('indicators', 'DisaggregationType')
    try:
        sadd_disagg = DisaggregationType.objects.get(pk=109)
    except DisaggregationType.DoesNotExist:
        return
    for indicator in Indicator.objects.all():
        indicator.disaggregation.add(sadd_disagg)

class Migration(migrations.Migration):

    dependencies = [
        ('indicators', '0081_remove_legacy_disaggregationvalue'),
    ]

    operations = [
        migrations.AlterField(
            model_name='disaggregationtype',
            name='country',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='workflow.Country', verbose_name='Country'),
        ),
        migrations.RunPython(remove_non_sadd_disaggregations, non_reversible_migration),
        migrations.RunPython(assign_sadd_to_all_existing_indicators, non_reversible_migration),
    ]
