# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-23 10:05
from __future__ import unicode_literals

from django.db import migrations, models


def copy_service_to_services_forward(apps, schema_editor):
    """Copy the service from ForeignKeyField to ManyToManyField."""
    Incident = apps.get_model("statusboard", "incident")
    db_alias = schema_editor.connection.alias
    for i in Incident.objects.using(db_alias).filter(service__isnull=False).all():
        i.services.add(i.service)
        i.save()


def copy_service_to_services_backward(apps, schema_editor):
    """Copy the first service from ManyToManyField to ForeignKeyField."""
    Incident = apps.get_model("statusboard", "incident")
    db_alias = schema_editor.connection.alias
    for i in Incident.objects.using(db_alias).all():
        s = i.services.first()
        if s is not None:
            i.service = s
            i.save()


class Migration(migrations.Migration):

    dependencies = [
        ('statusboard', '0015_close_previously_fixed_incidents'),
    ]

    operations = [
        migrations.AddField(
            model_name='incident',
            name='services',
            field=models.ManyToManyField(blank=True, related_name='incidents', related_query_name='incident', to='statusboard.Service', verbose_name='services'),
        ),
        migrations.RunPython(copy_service_to_services_forward,
                             copy_service_to_services_backward),
        migrations.RemoveField(
            model_name='incident',
            name='service',
        ),
    ]
