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

PACKET_PATH = 'migration.customizing.DB_39_5_7.wi14477_p_calc_periods.UpdatePeriodCalculationProcedureAgain'


class UpdatePeriodCalculationProcedureAgain(SQLPacket):
    """Update the procedure P_CALC_PERIODS with a bug fix"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 14477

    def get_dependencies(self):
        return (MinVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING),
                MaxVersionDependency(version='39.5.7', version_type=VersionType.CUSTOMIZING))

    def fix(self, packet_runner):
        packet = BasePacket.from_packet_path(PACKET_PATH)
        if packet is not None and packet.last_state == PacketState.INSTALLED:
            self.log('This packet is not necessary because the customizing packet that updates this procedure was '
                     'already installed')
            return self.success()

        self.modify_and_log('drop procedure "P_CALC_PERIODS"')
        self.apply_dml_file(self.sql_planta_de_dbms, 'wi14477_PLANTA_F_CALC_PERIOD_FACTOR.sql', split=False)

        return self.success()