# -*- coding: utf-8 -*-
from ppms.migration import ChangeDTPPacket, PacketCategory, MinVersionDependency, MaxVersionDependency, VersionType

OLD_MACRO = """mod_obj = ppms.get_target_module()
cur_macro_id = ppms.get_macro_module().get_id()

module_method=ppms.get_context_df().get_customizing_name()

if module_method != "":
    a="mod_obj.{0}()".format(module_method)
    try:
        exec(a)
    except:
        # case m4 macro call
        da_id=ppms.get_context_df().get_record().get_da().get_customizing().get_id()
        dtp_da = ppms.search_record(410, [da_id], [], True).get_children(411)

        python_id=ppms.db_select(ppms.get_query("000282").format(cur_macro_id,da_id))
        if len(python_id) == 1:
            a="mod_obj.{0}()".format(python_id[0][0])
            exec(a)"""
            
NEW_MACRO = """mod_obj = ppms.get_target_module()
cur_macro_id = ppms.get_macro_module().get_id()
module_method=ppms.get_context_df().get_customizing_name()
if module_method != "":
    a="mod_obj.{0}()".format(module_method)
    if hasattr(mod_obj,str(module_method)):
        exec(a)
    else:
        da_id=ppms.get_context_df().get_record().get_da().get_customizing().get_id()
        python_id=ppms.db_select(ppms.get_query("000282").format(cur_macro_id,da_id))
        if len(python_id) == 1:
            a="mod_obj.{0}()".format(python_id[0][0])
            exec(a)"""


class TryExceptSectionIgnoresErrorMessages(ChangeDTPPacket):
    """updates the macromodule 009AVG to execute without try/except"""

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

    def get_dependencies(self):
        return (MinVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING),
                MaxVersionDependency(version='39.5.4', version_type=VersionType.CUSTOMIZING))
        
    def fix(self, runner):
        current_macro_record = self.get_record(405, ['009AVG'], [40819])
        if current_macro_record is not None:
            if self.change_value(current_macro_record, "py_macro_text", OLD_MACRO, NEW_MACRO):
                return self.success()
        return self.fail("Could not update the current macro")