# -*- coding: utf-8 -*-
from ppms import ppms
from ppms.migration import SQLPacket, PacketCategory, MinVersionDependency, MaxVersionDependency


class DeleteDummyData(SQLPacket):
    """Update a few tables to not point at non-existent "-" data"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 18975

    def get_dependencies(self):
        return (MinVersionDependency(version='39.5.7'),
                MaxVersionDependency(version='39.5.7'))

    def get_recursive_relations(self):
        dd = ppms.get_data_dictionary()

        relations = []
        for relation in dd.relations.values():
            # We only care about recursive relations
            if relation.recursion_type != 'inner':
                continue

            # Dummy records are the whole reason for this packet
            if not relation.foreign_table.has_dummies:
                continue

            # Don't know what this stuff is
            if relation.name.endswith('reversed'):
                continue

            parents = relation.local_dis

            # Don't need to implement complex tables as they don't have corrupt data that we know of
            if len(parents) > 1:
                continue

            relations.append(relation)

        return relations

    def column_is_fixable(self, table_name, column_name):
        if self.get_column_type(table_name=table_name, column_name=column_name) in ('NUMERIC', 'NUMBER'):
            return False

        return True

    def fix_dummy_records_for_relation(self, relation):
        parents = relation.local_dis
        table = relation.table.sql_name
        foreign_key = parents[0].sql_name

        if not self.column_is_fixable(table_name=table, column_name=foreign_key):
            return 0

        query = "UPDATE {table} SET {foreign_key} = NULL WHERE {foreign_key} = '-'"

        self.log('Now updating {}'.format(table))
        formatted_query = query.format(table=table, foreign_key=foreign_key)

        return self.modify_and_log(formatted_query)

    def fix(self, packet_runner):
        relations = self.get_recursive_relations()
        for relation in relations:
            self.fix_dummy_records_for_relation(relation=relation)

        return self.success()
