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

from django.db import models, migrations
import django.utils.timezone
from django.conf import settings

def populate_trainings_owners(apps, schema_editor):
    """Populate the owners of the newly ``Versionable`` trainings."""

    Training = apps.get_model('trainings', 'Training')
    MTPUser = apps.get_model(
        settings.AUTH_USER_MODEL.split('.')[0],
        settings.AUTH_USER_MODEL.split('.')[1]
    )
    db_alias = schema_editor.connection.alias

    admin_user = MTPUser.objects.using(db_alias).filter(
            is_superuser=True).first()

    for training in Training.objects.using(db_alias).all():
        training.owner = admin_user
        training.save(using=db_alias)

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('trainings', '0015_add_nullable_owner_field'),
    ]

    operations = [
        migrations.RunPython(
            populate_trainings_owners
        ),
    ]
