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


class AddIndexesOnColumnsForDataTableListbox(SQLPacket):
    """Add indexes on columns related to the data table listbox"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 14166

    COLUMNS = (('DT411', 'DI000213'),
               ('DT412', 'DI000239'))

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

    def add_index(self, table, column):
        query = "CREATE INDEX IDX_{column} ON {table}({column})"

        try:
            if not self.change_create_index_to_rename_index(query.format(column=column, table=table)):
                self.modify_and_log(query.format(column=column, table=table))
        except ppms.DatabaseError as e:
            self.log('Column is probably already indexed...')

    def fix(self, packet_runner):
        for table, column in self.COLUMNS:
            self.add_index(table, column)

        return self.success()