# Generated by Django 2.0.2 on 2018-03-11 18:54
from collections import defaultdict
from typing import List

from django.db import migrations


def get_attributes_display_map(obj, attributes):
    """Return attributes associated with an object, as dict of AttrPK: AttributeValue.

    Args:
        obj: The variant or product.
        attributes: Attribute Iterable

    """
    display_map = defaultdict(str)
    for attribute in attributes:
        attribute_values = obj.attributes.get(str(attribute.pk))  # type: List
        if attribute_values:
            choices = {str(a.pk): a.translated for a in attribute.values.all()}
            for value in attribute_values:
                current_display_value = display_map[attribute.pk]
                if not current_display_value:
                    current_display_value = choices[value]
                else:
                    current_display_value = f"{current_display_value}, {choices[value]}"
                display_map[attribute.pk] = current_display_value
    return display_map


def get_name_from_attributes(variant):
    attributes = variant.product.product_type.variant_attributes.all()
    values = get_attributes_display_map(variant, attributes)
    return " / ".join(
        attributechoice.name
        for attribute_pk, attributechoice in sorted(values.items(), key=lambda x: x[0])
    )


def create_variant_name_based_on_attributes(apps, schema_editor):
    ProductVariant = apps.get_model("product", "ProductVariant")
    for variant in ProductVariant.objects.prefetch_related(
        "product__product_type__variant_attributes__values"
    ):
        new_name = get_name_from_attributes(variant)
        if variant.name != new_name:
            variant.name = new_name
            variant.save()


class Migration(migrations.Migration):

    dependencies = [("product", "0058_auto_20180329_0142")]

    operations = [
        migrations.RunPython(
            create_variant_name_based_on_attributes, migrations.RunPython.noop
        )
    ]
