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

from django.db import migrations, models

import mtp.apps.trainings.models


def update_session_states(apps, schema_editor):
    """Update the session instances with news states."""

    TrainingSession = apps.get_model("trainings", "TrainingSession")

    TrainingSession.objects.filter(
        state='be'
    ).update(
        state=mtp.apps.trainings.models.TrainingSession.STATE_CHOICES.NOT_YET_OPEN
    )

    TrainingSession.objects.filter(
        state='du'
    ).update(
        state=mtp.apps.trainings.models.TrainingSession.STATE_CHOICES.OPEN
    )

    TrainingSession.objects.filter(
        state='af'
    ).update(
        state=mtp.apps.trainings.models.TrainingSession.STATE_CHOICES.CLOSED
    )


def revert_session_states(apps, schema_editor):
    """Unupdate the session instances with news states.

    But information was lost during the update, we can't reset exactly in the previous state.
    We can only reset the open sessions with their previous code.

    """

    TrainingSession = apps.get_model("trainings", "TrainingSession")

    TrainingSession.objects.filter(
        state=mtp.apps.trainings.models.TrainingSession.STATE_CHOICES.OPEN
    ).update(
        state='du'
    )


class Migration(migrations.Migration):

    dependencies = [
        ('trainings', '0034_add_training_task_model'),
    ]

    operations = [
        migrations.RunPython(
            update_session_states,
            revert_session_states
        ),
        migrations.AlterField(
            model_name='trainingsession',
            name='state',
            field=models.CharField(default='no', max_length=2, db_index=True, choices=[('no', 'Ready for launch'), ('op', 'Ongoing'), ('cl', 'Closed')], verbose_name='state'),
        ),
    ]
