# -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2017-02-22 01:12
from __future__ import unicode_literals

from django.db import migrations
from django.db.models import F


class Migration(migrations.Migration):

    dependencies = [
        ('aims', '0010_openly_sector_type'),
    ]

    def set_national_sector_vocabularies(apps, schema_editor):
        ''' set the vocabulary to RO on all ActivitySector models which link to National sectors '''
        NationalSector = apps.get_model('aims', 'NationalSector')
        ActivitySector = apps.get_model('aims', 'ActivitySector')
        all_national_sector_links = ActivitySector.objects.filter(sector__local_data__in=NationalSector.objects.all())
        all_national_sector_links.update(vocabulary_id='RO')

    def remove_activitysectors_with_no_sector(apps, schema_editor):
        ''' Remove all ActivitySector models which have null sector references '''
        ActivitySector = apps.get_model('aims', 'ActivitySector')
        all_empty_sector_links = ActivitySector.objects.filter(sector__isnull=True)
        all_empty_sector_links.delete()

    def set_dac_activitysectors_vocalbulary(apps, schema_editor):
        ''' Set the vocabulary to DAC-5 or DAC-3 on all ActivitySectors referring to iati sectors
        DAC-5, where the sector's category code is not the same as the sector
        DAC-3, where the sector's category code IS the same as the sector
        '''
        ActivitySector = apps.get_model('aims', 'ActivitySector')
        dac3_sector_links = ActivitySector.objects.filter(sector__category__local_data__openly_type='iati', sector__category_id=F('sector__code'))
        dac5_sector_links = ActivitySector.objects.filter(sector__category__local_data__openly_type='iati').exclude(sector__category_id=F('sector__code'))
        dac3_sector_links.update(vocabulary_id='DAC-3')
        dac5_sector_links.update(vocabulary_id='DAC-5')

    operations = [
        migrations.RunPython(set_national_sector_vocabularies),
        migrations.RunPython(remove_activitysectors_with_no_sector),
        migrations.RunPython(set_dac_activitysectors_vocalbulary),
    ]
