from ppms import ppms
from ppms.constants import DBMS_ORACLE, DBMS_MSSQL
from ppms.migration import SQLPacket, PacketCategory


class AddIndexes(SQLPacket):
    """Create new indexes on DTs 467, 472 for performance enhancements"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 21253

    sql_script = 'WI21253_add_indexes.sql'

    def get_drop_statement(self, table_name, index_name):
        dbms = ppms.db_get_dbms_name()

        if dbms == DBMS_ORACLE:
            return 'DROP INDEX {}'.format(index_name)
        elif dbms == DBMS_MSSQL:
            return 'DROP INDEX {} ON {}'.format(index_name, table_name)
        else:
            raise ValueError(dbms)

    def fix(self, packet_runner):
        index_names = ['dt467_start_end_date_by_id', 'dt472_res_and_per_date']
        tables = ['DT467', 'DT472']

        for table, index_name in zip(tables, index_names):
            if self.index_exists(table_name=table, index_name=index_name):
                statement = self.get_drop_statement(table_name=table, index_name=index_name)
                self.modify_and_log(statement)
            else:
                self.log('Index {} does not exist and therefor does not need to be dropped!'.format(index_name))

        self.apply_fix_ddl_file(self.sql_planta_de_dbms, self.sql_script, split=True)

        return self.success()
