# -*- coding: utf-8 -*-
import io
import traceback
from ppms import ppms
from ppms.migration import SQLPacket, PacketCategory, get_packet_instance_from_path, PacketDependency, PacketState
from ppms.constants import DBMS_MSSQL

class SetObsoletePacketToSucceed(SQLPacket):
    """Packet DB_39_5_7/FixViewColumnLength may have failed under certain circumstances, but packet DB_39_5_7/FixLoadAutoNumber would have already corrected that"""
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 19138

    FAILING_PACKET_PATH = 'migration.customizing.DB_39_5_7.WI14340_fix_view_column_length.FixViewColumnLength'
    CORRECTING_PACKET_PATH = 'migration.customizing.DB_39_5_7.WI17300_fix_load_auto_nr.FixLoadAutoNumber'

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

    def fix(self, runner):
        if self.DBMS == DBMS_MSSQL:
            # In case of MSSQL for Linux, FixViewColumnLength might have failed due to capital error (dt instead of DT).
            # But, FixLoadAutoNumber would have fixed that anyway. -> So, declare FixViewColumnLength to be solved, now
            uuid = ppms.db_select("select uuid from MIGRATIONRULE where pythonpath='{path}'".format(path=self.FAILING_PACKET_PATH))[0][0]
            spurious_packet = get_packet_instance_from_path(self.FAILING_PACKET_PATH, uuid=uuid)

            spurious_packet.log("Declaring FixViewColumnLength to be solved since FixLoadAutoNumber has succeeded")
            spurious_packet.success()
            spurious_packet.save_history()

        else:
            self.log("This migration packet is only relevant for MSSQL.")

        return self.success()