# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-13 11:10
from __future__ import unicode_literals

from itertools import chain

from django.db import migrations
from django.utils import translation


def move_all_color_into_groups(apps, schema_editor):
    LocationGroupCategory = apps.get_model('mapdata', 'LocationGroupCategory')
    category = LocationGroupCategory.objects.get(name='groups')

    colors = {}
    for model_name in ('Level', 'Space', 'Area', 'POI'):
        model = apps.get_model('mapdata', model_name)
        for obj in model.objects.filter(color__isnull=False):
            colors.setdefault(obj.color, []).append(obj)

    from c3nav.mapdata.models import Location
    for color, objects in colors.items():
        titles = {lang: [] for lang in set(chain(*(obj.titles.keys() for obj in objects)))}
        for obj in objects:
            for lang in titles.keys():
                translation.activate(lang)
                titles[lang].append(Location(titles=obj.titles).title)
                translation.deactivate_all()
        titles = {lang: ', '.join(values) for lang, values in titles.items()}
        group = category.groups.create(can_search=False, can_describe=False, color=color, titles=titles)
        for obj in objects:
            obj.groups.add(group)


class Migration(migrations.Migration):

    dependencies = [
        ('mapdata', '0025_remove_area_stuffed'),
    ]

    operations = [
        migrations.RunPython(move_all_color_into_groups),
        migrations.RemoveField(
            model_name='area',
            name='color',
        ),
        migrations.RemoveField(
            model_name='level',
            name='color',
        ),
        migrations.RemoveField(
            model_name='poi',
            name='color',
        ),
        migrations.RemoveField(
            model_name='space',
            name='color',
        ),
    ]
