# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-10-25 09:33
from __future__ import unicode_literals

from django.db import migrations


def migrate_options(apps, schema_editor):

    Option = apps.get_model('options', 'Option')
    OptionSet = apps.get_model('options', 'OptionSet')
    OldOption = apps.get_model('domain', 'Option')

    attribute_ids = set(OldOption.objects.values_list('attribute', flat=True))
    for attribute_id in attribute_ids:

        # create an OptionSet for this attribute_id
        optionset = OptionSet.objects.create(
            title=attribute_id,
            order=0,
        )

        # attribute = Attribute.objects.filter(pk=attribute_id)
        # attribute.optionsets.add(optionset)
        # attribute.save()

        old_options = OldOption.objects.filter(attribute=attribute_id)

        # add the optionset to the attribute
        attribute = old_options.first().attribute
        attribute.optionsets.add(optionset)
        attribute.save()

        # loop over old options for this attribute and create new options
        for option in old_options:

            Option.objects.create(
                pk=option.pk,
                optionset=optionset,
                order=option.order,
                title=option.pk,
                text_en=option.text_en,
                text_de=option.text_de,
                additional_input=option.additional_input
            )


class Migration(migrations.Migration):

    dependencies = [
        ('options', '0002_meta'),
        ('domain', '0021_options'),
        ('projects', '0009_options'),
    ]

    operations = [
        migrations.RunPython(migrate_options),
    ]
