# -*- coding: utf-8 -*-
from ppms.migration import ChangeDTPPacket, PacketCategory, \
    MaxVersionDependency, MinVersionDependency, \
    PacketDependency, SinglePacketRunner, PacketState, BasePacket
from ppms.server_constants import *
from ppms import ppms

class ActivateRelationCheck(ChangeDTPPacket):
    """Run the relationcheck migration packages if not done already"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 16795

    def get_dependencies(self):
        return (MinVersionDependency(version='39.4'),
                MaxVersionDependency(version='39.4'))

    def fix(self, runner):
        package_failed = False
        PACKETS = ['migration.hotfix.S_39_5_8.wi9209_relationcheck.A_ChangeLBdigit',
                   'migration.hotfix.S_39_5_8.wi9209_relationcheck.B_ChangeLBvalue',
                   'migration.hotfix.S_39_5_8.wi9209_relationcheck.C_ChangeCustomizing',
                   'migration.hotfix.S_39_5_8.wi9209_relationcheck.D_ChangeModuleName',
                   'migration.hotfix.S_39_5_8.wi9209_relationcheck.E_CreateMacro',
                   'migration.hotfix.S_39_5_8.wi9209_relationcheck.F_ChangeMacroOfRelationCheck']
                   
        for packet_path in PACKETS:
            packet = BasePacket.from_packet_path(packet_path)
            uuid = packet.migrationrule
            
            self.log('Running {packet_path}...'.format(**locals()))
            
            if packet.last_state == PacketState.NEW:
                runner = SinglePacketRunner(uuid)
                
                with ppms.messages_disabled(), \
                      ppms.autoreply_to_message(message_id='0955', reply=MSG_REPLY_YES):
                    runner.run()
                
                if packet.last_state == PacketState.INSTALLED:
                    self.log('Packet installed.')
                else:
                    self.log('Something went wrong... please check packet log for details')
                    
            elif packet.last_state == PacketState.INSTALLED:
                self.log('Already installed! Nothing to do here.')
        
        if package_failed:
            return self.fail()
        else:
            return self.success()