# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2020-01-21 19:50
from __future__ import unicode_literals

from django.db import migrations, models, transaction
import uuid

from django.db.models import Subquery

from common.models import Case as CaseModel


def copy_uuids(apps, schema_editor):
    Case = apps.get_model("common", "Case")
    for case in Case.objects.all():
        case.tag = uuid.UUID(case.tag_text)
        case.save()


def is_valid_uuid4(uniq_id):
    try:
        uuid.UUID(uniq_id)
        return True
    except ValueError as e:
        print(e)
        print('uniq id: {}'.format(uniq_id))
        return False


def move_uuids_from_data(apps, schema_editor):
    Data = apps.get_model("common", "Data")
    Case = apps.get_model("common", "Case")
    rm_uuids_overall(apps, schema_editor)
    new_cases = [Case(data=data,
                      name=CaseModel.OVERALL,
                      tag=uuid.UUID(data.uniq_id),
                      tag_text=data.uniq_id)
                 for data in Data.objects.exclude(uniq_id__in=Subquery(Case.objects.all().values('tag_text'))).all()
                 if is_valid_uuid4(data.uniq_id)]
    Case.objects.bulk_create(new_cases)


def rm_uuids_overall(apps, schema_editor):
    Case = apps.get_model("common", "Case")
    Case.objects.filter(name=CaseModel.OVERALL).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('common', '0022_case_data'),
    ]

    operations = [
        migrations.AddField(
            model_name='case',
            name='tag',
            field=models.UUIDField(blank=True, null=True),
        ),
        migrations.RunPython(copy_uuids,
                             reverse_code=lambda a, se: None),
        migrations.RunPython(move_uuids_from_data,
                             reverse_code=rm_uuids_overall),
        # migrations.AlterField(
        #     model_name='case',
        #     name='tag',
        #     field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True),
        # ),
    ]
