# -*- coding: utf-8 -*-
import re

from ppms.migration.packet import *

HASHES = {'0099SY': ('baf1e4e952d64df7c028a29b87a3f807', '8f87d3a91903c322e2da0015ffa2cb7a'),
          '009B5V': ('71696147fc4a5d8945eb183867b7d211', 'd79de12f4e44d56120eb38de4b2352b5')}

PATTERN = re.compile('if mod_obj.+\(49\)', re.DOTALL)

class FixFilterMacro(MigratePythonPacket):
    '''Fix error in the objectfilter module.

    Fixes an error that lead to an assertion failure.
    This packet fails if there have been changes to the modules '0099SY' or '009B5V'.
    '''

    wi_number = 10460
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY

    def fix(self, runner):
        fix_func = lambda code: re.sub(PATTERN, '', code, 1)

        errors = 0
        for mod_id, (before_hash, after_hash) in HASHES.items():
           if not self.migrate_python(before_hash, after_hash,
                                      self.CU_TYPE_MODULE, mod_id, fix_func):
               errors += 1

        if errors > 0:
            return self.fail('Could not change all macros automatically!')

        return self.success()
