# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-07-21 12:07
from __future__ import unicode_literals
import re

from django.db import migrations, transaction

def parse_email_addresses(entry):
    match = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', entry.to)
    return match


def move_to_m2m(apps, schema_editor):
    LogEntry = apps.get_model('utils', 'LogEntry')
    ToAddress = apps.get_model('utils', 'ToAddress')

    email_log_entries = LogEntry.objects.filter(to__isnull=False)

    for entry in email_log_entries:
        with transaction.atomic():
            email_addresses = parse_email_addresses(entry)

            for email in email_addresses:
                ToAddress.objects.create(
                    email=email,
                    log_entry=entry,
                )


def move_to_string(apps, schema_editor):
    LogEntry = apps.get_model('utils', 'LogEntry')

    all_log_entries = LogEntry.objects.all()

    for entry in all_log_entries:
        if entry.toaddress_set.all().exists():
            to_string = [to.email for to in entry.toaddress_set.all()]
            entry.to = to_string
            entry.save()


class Migration(migrations.Migration):

    dependencies = [
        ('utils', '0016_auto_20200721_1419'),
    ]

    operations = [
        migrations.RunPython(move_to_m2m, reverse_code=move_to_string),
    ]

# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-07-21 12:07
from __future__ import unicode_literals
import re

from django.db import migrations, transaction

def parse_email_addresses(entry):
    match = re.findall(r'[\w\.\+-]+@[\w\.-]+\.\w+', entry.to)
    return match


def move_to_m2m(apps, schema_editor):
    LogEntry = apps.get_model('utils', 'LogEntry')
    ToAddress = apps.get_model('utils', 'ToAddress')

    email_log_entries = LogEntry.objects.filter(to__isnull=False)

    for entry in email_log_entries:
        email_addresses = parse_email_addresses(entry)
        for email in email_addresses:
            ToAddress.objects.create(
                email=email,
                log_entry=entry,
            )


def move_to_string(apps, schema_editor):
    LogEntry = apps.get_model('utils', 'LogEntry')

    all_log_entries = LogEntry.objects.all()

    for entry in all_log_entries:
        if entry.toaddress_set.all().exists():
            to_string = [to.email for to in entry.toaddress_set.all()]
            entry.to = to_string
            entry.save()


class Migration(migrations.Migration):

    dependencies = [
        ('utils', '0016_auto_20200721_1419'),
    ]

    operations = [
        migrations.RunPython(move_to_m2m, reverse_code=move_to_string),
    ]

Address comments from #1714