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

from ppms.migration.packet import *

class FindCmpUsagePacket(DeprecatedPythonPacket):
    '''Find the usage of the cmp(a, b) function in the Python-Code
    
    The cmp(a, b) function was removed in Python 3.2. This packet will point out
    where it is used in your Python code. If you still need it you can use this:

    def cmp(a, b):
        return (a > b) - (a < b)
    '''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_HELPER
    wi_number = 10527

    def get_matching_objects(self, iterable_to_filter):
        search = lambda x: re.search(r'\bcmp(?:\(.+?,.+?\))', x.source)

        # Load the full thing into memory, we don't have that much source code :P
        return list(filter(search, iterable_to_filter))

BEFORE_HASH = 'bee688136b2af96789ffad6c72e8c6af'
AFTER_HASH = '1afe0da8344e61cf8220103d1855d8b8'

REPLACEMENT = '''
        dev_ed = rec.dev_ed.get_value()
        dev_prev_ed = rec.dev_prev_ed.get_value()
        return dispatch[(dev_ed > dev_prev_ed) - (dev_ed < dev_prev_ed)]'''


class FixCmpPacket(MigratePythonPacket):
    '''Replace the usage of the cmp(a, b) function in the PLANTA customizing'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 10527

    def fix(self, runner):
        fix = lambda code: re.sub(r'\s.+return dispatch.+?]', REPLACEMENT,
                                  code, 1)

        if self.migrate_python(BEFORE_HASH, AFTER_HASH, self.CU_TYPE_DATAITEM,
                               '029843', fix):
            return self.success()

        return self.fail()
