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

from django.db import migrations, models


def set_trainning_field_null_for_live_activities(apps, schema_editor):
    """Set training field null for all live activities """

    TrainingActivity = apps.get_model(
        "trainings",
        "TrainingActivity"
    )
    live_activities = TrainingActivity.objects.exclude(session=None)
    live_activities.update(training=None)


def set_trainning_field_equal_session_training_field_for_live_activities(apps, schema_editor):
    """Set training field equal session.training for all live activities """

    TrainingActivity = apps.get_model(
        "trainings",
        "TrainingActivity"
    )
    live_activities = TrainingActivity.objects.exclude(session=None)
    live_activities.update(training=F('session__training'))


class Migration(migrations.Migration):
    dependencies = [
        ('trainings', '0043_trainingactivity_session'),
    ]

    operations = [
        migrations.AlterField(
            model_name='trainingactivity',
            name='training',
            field=models.ForeignKey(verbose_name='training', blank=True, null=True, to='trainings.Training', related_name='activities'),
        ),
        migrations.AlterUniqueTogether(
            name='trainingactivity',
            unique_together=set([('sort_order', 'training', 'session')]),
        ),
        migrations.RunPython(
            set_trainning_field_null_for_live_activities,
            set_trainning_field_equal_session_training_field_for_live_activities
        ),
        migrations.RunSQL(
            """
            ALTER TABLE trainings_trainingactivity ADD CONSTRAINT chk_training_or_session_not_together CHECK (
                (training_id is not null or session_id is not null)
                and
                (training_id is null or session_id is null)
            );
            """,
            """
            ALTER TABLE trainings_trainingactivity DROP CONSTRAINT chk_training_or_session;
            """
        )
    ]
