# -*- coding: utf-8 -*-
from ppms.constants import *
from ppms.migration import *


class DeleteUnusedColumns(SQLPacket, SucceedOldPacket):
    """Deactivates and drops unused if HF 14/DeleteUnusedColumns failed"""
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 14296

    helper_packet = 'migration.server.S_39_5_17.WI14269_0_mssql_helper_functions.MSSQLHelperFunctions'
    packet_to_correct = 'migration.hotfix.S_39_5_14.WI13544_delete_unused_columns.DeleteUnusedColumns'

    def get_dependencies(self):
        return (PacketDependency(packet_path=self.helper_packet, expected_state=PacketState.INSTALLED))

    def fix(self, runner):
        potentially_failed_packet = BasePacket.from_packet_path(self.packet_to_correct)

        # If potentially_failed_packet succeeded, after all, there is nothing to do
        if potentially_failed_packet is not None and potentially_failed_packet.last_state == PacketState.FAILED:
            if self.DBMS == DBMS_MSSQL:
                columns = ("'DT467', 'DI041591'",
                           "'DT467', 'DI042956'",
                           "'DT472', 'DI042011'",
                           "'DT472', 'DI042012'",
                           "'DT472', 'DI042013'",
                           "'DT472', 'DI042223'",
                           "'DT527', 'DI041348'")

                for column in columns:
                    self.modify_or_log("EXEC DropColumnWithConstraints {column}".format(column = column))

                self.mark_packet_as_done(self.packet_to_correct)

        return self.success()