# Generated by Django 3.1.7 on 2021-03-21 10:45
import logging

from django.db import migrations, models, transaction
from django.db.models import Case, When, Q, Value as V, F
from django.db.models.functions import Cast, Replace
from django.db.utils import ProgrammingError


logger = logging.getLogger(__name__)


def transform_success_to_status(apps, schema_editor):
	db_alias = schema_editor.connection.alias
	Email = apps.get_model('django_email_log.Email')
	char_field = models.CharField(max_length=1)
	transform = Case(
		When(Q(success=True), then=V('s')),
		default=V('f'), output_field=char_field
	)
	Email.objects.using(db_alias).annotate(new_value=transform).update(status=F('new_value'))


def transform_status_to_success(apps, schema_editor):
	db_alias = schema_editor.connection.alias
	Email = apps.get_model('django_email_log.Email')
	bool_field = models.BooleanField()
	transform = Case(
		When(Q(status='f'), then=V(False)),
		default=V(True), output_field=bool_field
	)
	Email.objects.using(db_alias).annotate(new_value=transform).update(success=F('new_value'))


def copy_message_data(apps, schema_editor):
	db_alias = schema_editor.connection.alias
	Email = apps.get_model('django_email_log.Email')
	if schema_editor.connection.vendor == 'postgresql':
		with transaction.atomic():
			try:
				cursor = schema_editor.connection.cursor()
				cmd = 'ALTER TABLE "django_email_log_email" ALTER COLUMN "message_data_tmp" SET STORAGE EXTERNAL;'
				cursor.execute(cmd)
			except ProgrammingError as e:
				logger.warning(str(e))
				logger.warning("SQL command failed:\n%s\n" % cmd)
				transaction.rollback()
		Email.objects.using(db_alias).update(message_data_tmp=Cast(Replace('message_data', V('\\'), V('\\\\')), output_field=models.BinaryField()))
	else:
		Email.objects.using(db_alias).update(message_data_tmp=Cast('message_data', output_field=models.BinaryField()))


def uncopy_message_data(apps, schema_editor):
	db_alias = schema_editor.connection.alias
	Email = apps.get_model('django_email_log.Email')
	Email.objects.using(db_alias).update(message_data=Cast('message_data_tmp', output_field=models.TextField()))


class Migration(migrations.Migration):

	dependencies = [
		('django_email_log', '0001_initial'),
	]

	operations = [
		migrations.AddField(
			model_name='email',
			name='readed',
			field=models.BooleanField(blank=True, db_index=True, default=False, verbose_name='readed'),
		),
		migrations.AddField(
			model_name='email',
			name='status',
			field=models.CharField(choices=[('p', 'Pending'), ('s', 'Success'), ('f', 'Fail'), ('r', 'Received')], db_index=True, default='p', max_length=1, verbose_name='status'),
		),
		migrations.RunPython(transform_success_to_status, transform_status_to_success),
		migrations.RemoveField(
			model_name='email',
			name='success',
		),
		migrations.AlterField(
			model_name='email',
			name='message_data',
			field=models.TextField(verbose_name='data', default=''),
		),
		migrations.AddField(
			model_name='email',
			name='message_data_tmp',
			field=models.BinaryField(default=b''),
		),
		migrations.RunPython(copy_message_data, uncopy_message_data),
		migrations.RemoveField(
			model_name='email',
			name='message_data',
		),
		migrations.RenameField(
			model_name='email',
			old_name='message_data_tmp',
			new_name='message_data',
		),
		migrations.AlterField(
			model_name='email',
			name='message_data',
			field=models.BinaryField(),
		),
	]
