# Generated by Django 2.2.7 on 2019-12-17 09:13

from django.db import migrations, models
import django.db.models.deletion
from django.core.exceptions import ObjectDoesNotExist


def migrate_task_data(apps, schema_editor):
    task_model = apps.get_model("ops", "Task")
    db_alias = schema_editor.connection.alias
    tasks = task_model.objects.using(db_alias).all()
    for task in tasks:
        try:
            latest_history = task.history.latest()
        except ObjectDoesNotExist:
            latest_history = None
        try:
            latest_adhoc = task.adhoc.latest()
        except ObjectDoesNotExist:
            latest_adhoc = None
        if latest_history and latest_history.adhoc:
            latest_history.hosts_amount = latest_history.adhoc.hosts.count()
            latest_history.save()
        total_run_amount = task.history.all().count()
        success_run_amount = task.history.filter(is_success=True).count()
        task.latest_history = latest_history
        task.latest_adhoc = latest_adhoc
        task.total_run_amount = total_run_amount
        task.success_run_amount = success_run_amount
        task.save()


class Migration(migrations.Migration):

    dependencies = [
        ('ops', '0008_auto_20190919_2100'),
    ]

    operations = [
        migrations.AddField(
            model_name='task',
            name='latest_adhoc',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='task_latest', to='ops.AdHoc'),
        ),
        migrations.AddField(
            model_name='task',
            name='latest_history',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='task_latest', to='ops.AdHocRunHistory'),
        ),
        migrations.AddField(
            model_name='task',
            name='success_run_amount',
            field=models.IntegerField(default=0),
        ),
        migrations.AddField(
            model_name='task',
            name='total_run_amount',
            field=models.IntegerField(default=0),
        ),
        migrations.AddField(
            model_name='adhocrunhistory',
            name='hosts_amount',
            field=models.IntegerField(default=0, verbose_name='Host amount'),
        ),
        migrations.AddField(
            model_name='adhocrunhistory',
            name='task_display',
            field=models.CharField(blank=True, default='', max_length=128,
                                   verbose_name='Task display'),
        ),
        migrations.RunPython(migrate_task_data),
    ]
