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


def copy_industries(apps, schema_editor):
    EmploymentHistory = apps.get_model('accounts', 'EmploymentHistory')
    Industry = apps.get_model('core', 'Industry')
    industries = {item.name.casefold(): item for item in Industry.objects.all()}
    for employment in EmploymentHistory.objects.exclude(industry=''):
        industry = industries.get(employment.industry.strip().casefold())
        if industry:
            employment.industry_relation = industry
            employment.save(update_fields=['industry_relation'])


class Migration(migrations.Migration):
    dependencies = [
        ('core', '0002_industry'),
        ('accounts', '0002_member_accountinvitation_and_more'),
    ]
    operations = [
        migrations.AddField(
            model_name='employmenthistory',
            name='industry_relation',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='employment_history', to='core.industry'),
        ),
        migrations.RunPython(copy_industries, migrations.RunPython.noop),
        migrations.RemoveField(model_name='employmenthistory', name='industry'),
        migrations.RenameField(model_name='employmenthistory', old_name='industry_relation', new_name='industry'),
    ]
