# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-09-10 18:20
from __future__ import unicode_literals

from django.db import migrations
from django.db import connection


def table_exists(tablename):
    cursor = connection.cursor()
    cursor.execute(
        """SELECT EXISTS (SELECT * FROM pg_tables WHERE tablename ='{}');""".format(tablename)
    )
    return cursor.fetchone()[0]

tables = [
    ('ashlar_boundary', 'grout_boundary'),
    ('ashlar_boundarypolygon', 'grout_boundarypolygon'),
    ('ashlar_recordtype', 'grout_recordtype'),
    ('ashlar_recordschema', 'grout_recordschema')
]


def forward(apps, schema_editor):
    cursor = connection.cursor()
    for ashlar_table, grout_table in tables:
        # Only rename the table if it exists and the corresponding grout table doesn't exist. If the
        # corresponding grout table exists, that means that migrations have been run from the
        # beginning without Ashlar having been installed, such as when testing, and we shouldn't do
        # anything.
        if table_exists(ashlar_table) and not table_exists(grout_table):
            cursor.execute('ALTER TABLE {a} RENAME TO {g};'.format(a=ashlar_table, g=grout_table))
    # The Record table needs special handling because we need to preserve some of the old Ashlar
    # data in DRIVER after Grout drops those columns, so we need to copy the table rather than
    # simply renaming it, so that we can pull in the dropped columns later from the old Ashlar
    # tables.
    if table_exists('ashlar_record') and not table_exists('grout_record'):
        cursor.execute('CREATE TABLE grout_record (LIKE ashlar_record INCLUDING ALL);')
        cursor.execute('INSERT INTO grout_record SELECT * FROM ashlar_record;')


def reverse(apps, schema_editor):
    cursor = connection.cursor()
    # The only time we would reverse is if we know that we previously used Ashlar, which we can only
    # know for sure if the `ashlar_record` table exists (since all other tables get renamed rather
    # than copied).
    if table_exists('ashlar_record'):
        for ashlar_table, grout_table in tables:
            cursor.execute('ALTER TABLE {g} RENAME TO {a};'.format(a=ashlar_table, g=grout_table))
        cursor.execute('DROP TABLE grout_record;')


class Migration(migrations.Migration):

    dependencies = [
        ('data', '0010_auto_20160527_2236'),
    ]

    operations = [
        migrations.RunPython(forward, reverse)
    ]
