# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-03-19 01:35
from __future__ import unicode_literals

import django.contrib.gis.db.models.fields
from django.db import migrations, models


def forwards(apps, schema_editor):
    Column = apps.get_model("seed", "Column")
    ColumnMapping = apps.get_model("seed", "ColumnMapping")
    Organization = apps.get_model("orgs", "Organization")
    # PropertyState = apps.get_model("seed", "PropertyState")

    new_db_fields = [
        {
            'column_name': 'latitude',
            'table_name': 'TaxLotState',
            'display_name': 'Latitude',
            'data_type': 'number',
        }, {
            'column_name': 'longitude',
            'table_name': 'TaxLotState',
            'display_name': 'Longitude',
            'data_type': 'number',
        },
        # The previous migration created a PropertyState ULID and not a TaxLotState ULID.
        # This fixes that issue.
        {
            'column_name': 'ulid',
            'table_name': 'TaxLotState',
            'display_name': 'ULID',
            'data_type': 'string',
        }
    ]

    # Go through all the organizatoins
    for org in Organization.objects.all():
        for new_db_field in new_db_fields:
            columns = Column.objects.filter(
                organization_id=org.id,
                table_name=new_db_field['table_name'],
                column_name=new_db_field['column_name'],
                is_extra_data=False,
            )

            if not columns.count():
                new_db_field['organization_id'] = org.id
                Column.objects.create(**new_db_field)
            elif columns.count() == 1:
                # If the column exists, then just update the display_name and data_type if empty
                c = columns.first()
                if c.display_name is None or c.display_name == '':
                    c.display_name = new_db_field['display_name']
                if c.data_type is None or c.data_type == '' or c.data_type == 'None':
                    c.data_type = new_db_field['data_type']
                c.save()
            else:
                print("  More than one column returned")

    # Go through and delete the PropertyState.ULID columns if there is no mapping to the column
    objs_to_delete = set()
    for org in Organization.objects.all():
        columns = Column.objects.filter(
            organization_id=org.id,
            table_name='PropertyState',
            column_name='ulid',
            is_extra_data=False,
        )

        if not columns.count():
            continue
        elif columns.count() == 1:
            # If the column exists, then check if it is used in mappings. If not, then
            # remove the object from the database
            c = columns.first()

            cms = ColumnMapping.objects.filter(column_mapped=c)
            if cms.count() == 0:
                # go ahead and delete the column since no data is mapping to this column
                # print("Removing unneeded PropertyState.ULID Column")
                objs_to_delete.add(c)
            elif cms.count() == 1:
                # there are data mapped to this column, need to check if the database has any
                # data in the extra data field of this column. This code is just a stub for now.
                # There needs to be some adequate testing to move data from extra_data to db fields.
                # pss = PropertyState.objects.filter(extra_data__ulid__isnull=False)
                # if pss.count() == 0:
                #     # there are no data, so delete the column and column mapping
                #     cms.first().delete()
                #     c.delete()
                # else:
                print("There are data in PropertyState.extra_data['ulid']!")
            else:
                # should never reach this.
                raise Exception("This should never have been reached!")
            c.save()
        else:
            raise Exception("  More than one column returned")

    if len(objs_to_delete):
        print("objects to delete:")
    for obj in objs_to_delete:
        print("  {}  --  {}.{}".format(obj.id, obj.table_name, obj.column_name))
        obj.delete()


class Migration(migrations.Migration):
    dependencies = [
        ('seed', '0100_auto_20190228_1239'),
    ]

    operations = [
        migrations.AddField(
            model_name='taxlotstate',
            name='centroid',
            field=django.contrib.gis.db.models.fields.PolygonField(blank=True, geography=True,
                                                                   null=True, srid=4326),
        ),
        migrations.AddField(
            model_name='taxlotstate',
            name='latitude',
            field=models.FloatField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='taxlotstate',
            name='longitude',
            field=models.FloatField(blank=True, null=True),
        ),
        migrations.RunPython(forwards),
    ]
