# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models


def set_state_for_finished_task(apps, schema_editor):
    """Mark all tasks having ``finished_at`` not ``None`` as ``SUCCESS``"""
    DjangoTask = apps.get_model('tasks', 'DjangoTask')
    db_alias = schema_editor.connection.alias
    DjangoTask.objects.using(db_alias).filter(finished_at__isnull=False).update(state='success')


def noop(*args, **kwargs):  # pylint: disable=unused-argument
    """Empty operation used for the reverse of ``set_state_for_finished_task``"""
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('tasks', '0003_remove_djangotask_data'),
    ]

    operations = [
        migrations.AddField(
            model_name='djangotask',
            name='state',
            field=models.CharField(verbose_name='State', max_length=8, default='pending', choices=[('failure', 'Failure'), ('pending', 'Pending'), ('received', 'Received'), ('retry', 'Retry'), ('revoked', 'Revoked'), ('started', 'Started'), ('success', 'Success')], db_index=True),
        ),
        migrations.RunPython(set_state_for_finished_task, reverse_code=noop),
    ]
