# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2022-10-21 12:33
from __future__ import unicode_literals

from django.db import migrations
from django.db.models import F
from django.core.exceptions import FieldDoesNotExist

def copy_fields_from_fieldchoice(apps, schema_editor):
    SemanticField = apps.get_model('dictionary', 'SemanticField')
    try:
        SemanticField.objects.all().update(name_en=F('name'))
        print("Copied SemanticField name to name_en")
    except FieldDoesNotExist:
        pass
    DerivationHistory = apps.get_model('dictionary', 'DerivationHistory')
    try:
        DerivationHistory.objects.all().update(name_en=F('name'))
        print("Copied DerivationHistory name to name_en")
    except FieldDoesNotExist:
        pass

    # Put all choices in a dict for convenient lookup
    FieldChoice = apps.get_model('dictionary', 'FieldChoice')
    semanticfieldchoicecolors = dict([(SemFieldchoice.machine_value, SemFieldchoice.field_color)
                                for SemFieldchoice in FieldChoice.objects.filter(field='SemField')])

    # Copy values for each SemanticField
    for semanticfield in SemanticField.objects.all():
        if semanticfield.machine_value in semanticfieldchoicecolors.keys():
            semanticfield.field_color = semanticfieldchoicecolors[semanticfield.machine_value]
            semanticfield.save()
        else:
            print('Missing SemField FieldChoice for machine value: ', semanticfield.machine_value)

    derivHistfieldchoicecolors = dict([(derivHistchoice.machine_value, derivHistchoice.field_color)
                                 for derivHistchoice in FieldChoice.objects.filter(field='derivHist')])

    # Copy values for each DerivationHistory
    for derivhist in DerivationHistory.objects.all():
        if derivhist.machine_value in derivHistfieldchoicecolors.keys():
            derivhist.field_color = derivHistfieldchoicecolors[derivhist.machine_value]
            derivhist.save()
        else:
            print('Missing derivHist FieldChoice for machine value: ', derivhist.machine_value)

    Handshape = apps.get_model('dictionary', 'Handshape')
    handshapefieldchoicecolors = dict([(handshapechoice.machine_value, handshapechoice.field_color)
                                 for handshapechoice in FieldChoice.objects.filter(field='Handshape')])

    # Copy values for each Handshape
    for handshape in Handshape.objects.all():
        if handshape.machine_value in handshapefieldchoicecolors.keys():
            handshape.field_color = handshapefieldchoicecolors[handshape.machine_value]
            handshape.save()
        else:
            print('Missing Handshape FieldChoice for machine value: ', handshape.machine_value)


class Migration(migrations.Migration):

    dependencies = [
        ('dictionary', '0050_auto_20221021_1310'),
    ]

    operations = [
        migrations.RunPython(copy_fields_from_fieldchoice),
    ]
