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


class ReplaceProcessModelActivationMacroWithSubclass(ChangeDTPPacket):
    """Replace the process model activation macro with a subclass"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13728

    SUBCLASS_PATH = 'ppms.module_subclasses.processes.ResetProcessModelMacro'
    OLD_CODE_A = """from ppms import ppms_cu
from ppms import processes
import imp
imp.reload(processes)

# Moduldaten
mod_obj=ppms.get_target_module()

ppms.ui_message_id("0774")

if ppms.msg_pop().get_reply() == 1:

    # invoker
    inv_rec=ppms.get_context_df().get_record()

    pr_id = inv_rec.get_dtp_record().pr_id.get_value()
    object_type = processes.get_object_type_by_pr_id(pr_id)

    processes.end_all_steps_and_reset_pm_model(pr_id,object_type)

    mod_obj.refresh_module()
"""

    OLD_CODE_B = """from ppms import ppms_cu
from ppms import processes
import imp
imp.reload(processes)

# Moduldaten
mod_obj=ppms.get_target_module()

ppms.ui_message_id("0774")

if ppms.msg_pop().get_reply() == 1:

    # invoker
    inv_rec=ppms.get_context_df().get_record()

    pr_id = inv_rec.get_dtp_record().pr_id.get_value()
    object_type = processes.get_object_type_by_pr_id(pr_id)

    processes.end_all_steps_and_reset_pm_model(pr_id,object_type)

    mod_obj.refresh_module()
"""

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

    def fix(self, runner):
        record = self.get_record(dt_num=405, key_list=['009BCA'], di_list=['py_macro_text', 'python_module_subclass'])
        if not self.change_value(record=record, attribute='py_macro_text', old_value=self.OLD_CODE_A, new_value=''):
            if not self.change_value(record=record, attribute='py_macro_text', old_value=self.OLD_CODE_B,
                                     new_value=''):
                return self.fail('Could not change macro 009BCA - was it individualized?')

        if not self.change_value(record=record, attribute='python_module_subclass', old_value='',
                                 new_value=self.SUBCLASS_PATH) and \
                not self.change_value(record, 'python_module_subclass', 'ppms.module_subclasses.base_class.Base',
                                      self.SUBCLASS_PATH):
            return self.fail('Could not change module subclass for module 009BCA - was it individualized?')

        return self.success()


class PortProcessModelActivationDialogMessage(SQLPacket):
    """Port the dialog message 1065 to Venus on Earth"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13728

    FILENAME = 'wi13728_activate_process_model.sql'

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

    def fix(self, runner):
        self.apply_dml_file(self.sql_planta_de_dbms, self.FILENAME)

        return self.success()


class ReplaceExecuteProcessActionMacroWithSubclass(ChangeDTPPacket):
    """Replace the process model action execution macro with a subclass"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13728

    SUBCLASS_PATH = 'ppms.module_subclasses.processes.ExecuteProcessActionMacro'
    OLD_CODE = r"""from ppms import processes

mod_obj=ppms.get_target_module()
inv_rec=ppms.get_context_df().get_record()
process_action_id=inv_rec.get_dtp_record().process_action_id.get_value()

if process_action_id:
    phase_rule = processes.get_process_rule_settings(process_action_id)
    ppms.get_session_dict()["planta_functions"]=[]
    exec(phase_rule[1].replace("\r\n","\n"))
    mod_obj.executeProcessAction = ppms.get_session_dict()["planta_functions"][0]

    mod_obj.executeProcessAction(inv_rec,inv_rec.get_dtp_record().object_id.get_value())
else:
    ppms.ui_message_id("0787")"""

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

    def fix(self, runner):
        record = self.get_record(dt_num=405, key_list=['009BAS'], di_list=['py_macro_text', 'python_module_subclass'])
        if not self.change_value(record=record, attribute='py_macro_text', old_value=self.OLD_CODE, new_value=''):
            return self.fail('Could not change macro 009BAS - was it individualized?')

        if not self.change_value(record=record, attribute='python_module_subclass', old_value='',
                                 new_value=self.SUBCLASS_PATH) and \
                not self.change_value(record, 'python_module_subclass', 'ppms.module_subclasses.base_class.Base',
                                      self.SUBCLASS_PATH):

            return self.fail('Could not change module subclass for module 009BAS - was it individualized?')

        return self.success()