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

import re

from datetime import timedelta
from django.db import migrations, models
from mtp.apps.common.utils import timedelta_to_string, string_to_timedelta


def convert_duration_field_to_char_field(apps, schema_editor):
    Lesson = apps.get_model("assessments", "Lesson")
    db_alias = schema_editor.connection.alias
    for lesson in Lesson.objects.using(db_alias).all():
        lesson.duration_text = timedelta_to_string(lesson.duration)
        lesson.save(using=db_alias)


def convert_char_field_to_duration_field(apps, schema_editor):
    Lesson = apps.get_model("assessments", "Lesson")
    db_alias = schema_editor.connection.alias
    for lesson in Lesson.objects.using(db_alias).all():
        lesson.duration = string_to_timedelta(lesson.duration_text)
        lesson.save(using=db_alias)


class Migration(migrations.Migration):

    dependencies = [
        ('assessments', '0016_add_lesson_references'),
    ]

    operations = [
        migrations.AddField(
            model_name='lesson',
            name='duration_text',
            field=models.CharField(max_length=100, blank=True),
        ),
        migrations.RunPython(
            convert_duration_field_to_char_field,
            convert_char_field_to_duration_field
        )
    ]
