# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-07-26 12:52
from __future__ import unicode_literals
import json
from dateutil import parser
from decimal import Decimal

from django.db import migrations, models
from django.core.serializers.json import DjangoJSONEncoder

from models_logging.settings import ADDED, CHANGED, DELETED


old_actions = {
    'Changed': CHANGED,
    'Added': ADDED,
    'Deleted': DELETED
}


def migrate_changed_data(apps, schema_editor):
    def _get_val(val):
        if 'None' in val:
            return None
        if val.isdigit():
            return int(val)
        try:
            return Decimal(val)
        except Exception:
            pass
        try:
            return parser.parse(val)
        except Exception:
            pass

        return val

    Change = apps.get_model('models_logging', 'Change')
    chunk = Change.objects.count() // 100
    perc = 0
    for count, ch in enumerate(Change.objects.using(schema_editor.connection.alias).all()):
        if count % chunk == 0:
            print('{}%'.format(perc))
            perc += 1
        comment = ch.comment.split(':\n')

        action = old_actions[ch.action]
        if action == DELETED:
            Change.objects.filter(id=ch.id).update(action=action)
            continue
        elif comment[0].startswith('Recover'):
            continue

        data = []
        try:
            for i in comment[1].split(')\n"'):
                d = i.split('" (')
                field = d[0].replace('"', '')
                vals = d[1].split('->')
                old = vals[0].lstrip('(').strip(' ')
                new = vals[1].rstrip(')').strip(' ')
                data.append({'field': field, 'values': {'old': _get_val(old), 'new': _get_val(new)}})
        except Exception:
            # some changes we must skip ;(
            pass
        changed_data = json.dumps(data, cls=DjangoJSONEncoder)
        Change.objects.filter(id=ch.id).update(action=action, changed_data=changed_data)


class Migration(migrations.Migration):
    dependencies = [
        ('models_logging', '0002_auto_20161012_2025'),
    ]

    operations = [
        migrations.RenameModel(
            old_name='Changes',
            new_name='Change',
        ),
        migrations.AddField(
            model_name='change',
            name='changed_data',
            field=models.TextField(blank=True, help_text='The old data of changed fields.', null=True),
        ),
        migrations.AlterField(
            model_name='change',
            name='action',
            field=models.CharField(choices=[('added', 'Added'), ('changed', 'Changed'), ('deleted', 'Deleted')],
                                   help_text='added|changed|deleted', max_length=7, verbose_name='Action'),
        ),
        migrations.RemoveField(
            model_name='change',
            name='serialized_data',
        ),
        migrations.RunPython(migrate_changed_data, migrations.RunPython.noop),
    ]
