# -*- coding: utf-8 -*-
# Generated by Django 1.9.8.dev20160616122412 on 2016-07-01 04:22
import json
from operator import itemgetter

import django.db.models.deletion
from django.db import migrations, models


def move_legend_entries_to_through_model(apps, schema_editor):
    """
    Move the data from the normal m2m table to the through table for legend entries.
    """
    Legend = apps.get_model("raster", "Legend")
    LegendEntryOrder = apps.get_model("raster", "LegendEntryOrder")
    for leg in Legend.objects.all():
        for entry in leg.entries.all():
            # Respect unique contraint.
            if LegendEntryOrder.objects.filter(legend=leg, legendentry=entry).exists():
                continue
            LegendEntryOrder.objects.create(
                legend=leg,
                legendentry=entry,
                code='',
            )
        # Make sure legend json is up to date.
        data = []
        for val in leg.legendentryorder_set.prefetch_related('legendentry').all():
            data.append({
                'name': val.legendentry.semantics.name,
                'expression': val.legendentry.expression,
                'code': val.code,
                'color': val.legendentry.color,
            })
        data = sorted(data, key=itemgetter('name'))
        leg.json = json.dumps(data)
        leg.save()


def move_legend_entries_from_through_model_to_normal_m2m(apps, schema_editor):
    """
    Move the data from the entries order table to the through table for legend entries.
    """
    Legend = apps.get_model("raster", "Legend")
    LegendEntryOrder = apps.get_model("raster", "LegendEntryOrder")
    for leg in Legend.objects.all():
        for enor in LegendEntryOrder.objects.filter(legend=leg):
            leg.entries.add(enor.legendentry)


class Migration(migrations.Migration):

    dependencies = [
        ('raster', '0033_auto_20160510_1041'),
    ]

    operations = [
        migrations.CreateModel(
            name='LegendEntryOrder',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('code', models.CharField(max_length=100, default='', blank=True)),
                ('legendentry', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='raster.LegendEntry')),
                ('legend', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='raster.Legend')),
            ],
        ),
        migrations.AlterUniqueTogether(
            name='legendentryorder',
            unique_together=set([('legend', 'legendentry')]),
        ),
        migrations.RunPython(move_legend_entries_to_through_model, move_legend_entries_from_through_model_to_normal_m2m),
        migrations.RemoveField(
            model_name='legend',
            name='entries',
        ),
        migrations.AddField(
            model_name='legend',
            name='entries',
            field=models.ManyToManyField(through='raster.LegendEntryOrder', to='raster.LegendEntry'),
        ),
    ]
