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


class AddIndexesOnColumnsForModuleListbox(SQLPacket):
    """Add indexes on columns related to the module listbox"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 16398

    COLUMNS = (('DT404', 'DI028100'),
               ('DT405', 'DI000123'),
               ('DT406', 'DI000970'),
               ('DT406', 'DI000969'),
               ('DT410', 'DI000198'),
               ('DT411', 'DI000306'))

    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()