# -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-08-14 17:59
from __future__ import unicode_literals

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

PROJECT_STATUS_ACTIVE = 0
PROJECT_STATUS_COMPLETED = 4

TASK_STATUS_COMPLETED = 5

def mark_completed_projects(apps, schema_editor):
    Project = apps.get_model('orchestra', 'Project')
    Task = apps.get_model('orchestra', 'Task')

    projects = Project.objects.filter(status=PROJECT_STATUS_ACTIVE)
    in_progress_projects = (
        Task.objects.exclude(status=TASK_STATUS_COMPLETED)
        .values_list('project', flat=True))
    completed_projects = (
        projects.annotate(num_tasks=Count('tasks'))
        .filter(num_tasks__gt=0)
        .exclude(id__in=in_progress_projects))

    for project in completed_projects:
        if (project.status == PROJECT_STATUS_ACTIVE):
            project.status = PROJECT_STATUS_COMPLETED
            project.save()


class Migration(migrations.Migration):

    dependencies = [
        ('orchestra', '0079_auto_20180806_1528'),
    ]

    operations = [
        migrations.AlterField(
            model_name='project',
            name='status',
            field=models.IntegerField(choices=[(0, 'Active'), (2, 'Aborted'), (3, 'Paused'), (4, 'Completed')], default=0),
        ),
        migrations.RunPython(mark_completed_projects)  # manually-reviewed
    ]
