# Generated by Django 2.2.11 on 2020-03-19 16:58

from django.db import migrations

from django_yubin import tasks


# To avoid dependeny with constants.py
RESULT_SENT = 0
RESULT_SKIPPED = 1
RESULT_FAILED = 2


def migrate_to_queues(apps, schema_editor):
    from django_yubin.models import Message as DBMessage

    Message = apps.get_model('django_yubin', 'Message')
    QueuedMessage = apps.get_model('django_yubin', 'QueuedMessage')
    Log = apps.get_model('django_yubin', 'Log')

    # Messages without a QueueMessage ara sent.
    for message in Message.objects.all():
        queued = QueuedMessage.objects.filter(message=message).only('date_queued').first()
        if queued:
            message.status = DBMessage.STATUS_QUEUED
            message.date_enqueued = queued.date_queued
            message.enqueued_count = 1
            message.save()
            tasks.send_email.delay(message.pk)
        else:
            message.status = DBMessage.STATUS_SENT
            message.sent_count = 1
            message.date_enqueued = message.date_sent
            message.enqueued_count = 1
            message.save()

    # Set Log actions based on its result
    for log in Log.objects.all():
        if log.result == RESULT_SENT:
            log.action = DBMessage.STATUS_SENT
        elif log.result == RESULT_FAILED:
            log.action = DBMessage.STATUS_FAILED
        elif log.result == RESULT_SKIPPED:
            log.action = DBMessage.STATUS_DISCARDED
        log.save()


class Migration(migrations.Migration):

    dependencies = [
        ('django_yubin', '0006_auto_20200319_1120'),
    ]

    operations = [
        migrations.RunPython(migrate_to_queues),
    ]
