# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-06-19 13:55
from __future__ import unicode_literals
import datetime
from django.db import migrations

def fix_phaselog_for_incorrect_project_statuses(apps, schema_editor):
    """
    #BB-9886 : Fix to add a new project phase status logs for projects whose status does not correspond to the last
    project phase status log. We have to fake a timestamp as we dont know when the status was really updated.
    """
    Project = apps.get_model('projects', 'Project')
    ProjectPhaseLog = apps.get_model('projects', 'ProjectPhaseLog')

    for project in Project.objects.all():
        last_project_phase_log = ProjectPhaseLog.objects.filter(project=project).order_by('start').last()
        if project.status != last_project_phase_log.status:
            start = last_project_phase_log.start + datetime.timedelta(minutes = 1)
            log = ProjectPhaseLog.objects.create(project=project, status=project.status, start=start)
            log.save()

def dummy(apps, schema_editor):
    pass

class Migration(migrations.Migration):

    dependencies = [
        ('projects', '0027_auto_20170602_2240'),
    ]

    operations = [
        migrations.RunPython(fix_phaselog_for_incorrect_project_statuses, dummy),
    ]

add migrations for missing phaselogs after fixing bulk project status updates