# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-06-08 06:58
from __future__ import unicode_literals
from functools import partial
import six
from django.db import migrations, models
from django.db.models.functions import Length


def __bulking_lines(history, value, number, obj_class):
    out = six.StringIO(value)
    for line in iter(partial(out.read, 2 * 1024 - 100), ''):
        yield obj_class(history=history, line_number=number, line=line)


def migrate_history_lines(apps, schema_editor):
    HistoryLines = apps.get_registered_model('main', 'HistoryLines')
    qs = HistoryLines.objects.annotate(line_len=Length('line'))
    qs = qs.filter(line_len__gt=2048)
    lines = []
    for hist_line in qs:
        history = hist_line.history
        value = hist_line.line
        number = hist_line.line_number
        hist_line.delete()
        lines += [l for l in __bulking_lines(history, value, number, HistoryLines)]
    HistoryLines.objects.bulk_create(lines)


class Migration(migrations.Migration):

    dependencies = [
        ('main', '0045_hook_enable'),
    ]

    operations = [
        migrations.RunPython(
            migrate_history_lines,
            reverse_code=migrations.RunPython.noop
        ),
        migrations.AlterField(
            model_name='historylines',
            name='line',
            field=models.CharField(default='', max_length=2048),
        ),
        migrations.AlterField(
            model_name='hook',
            name='recipients',
            field=models.CharField(max_length=20000),
        ),
        migrations.AlterField(
            model_name='template',
            name='options_data',
            field=models.TextField(default='{}'),
        ),
        migrations.AlterField(
            model_name='template',
            name='template_data',
            field=models.TextField(default='{}'),
        ),
    ]
