# -*- coding: utf-8 -*-
from ppms import ppms
from ppms.constants import *
from ppms.migration import SQLPacket, PacketCategory, MaxVersionDependency, VersionType, MinVersionDependency, \
    ChangeDTPPacket, PacketDependency, PacketState


ALTER_TABLE_STATEMENTS = {DBMS_ORACLE: ("alter table DT496 add CAN_DELETE number(5,0) default 1",
                                        "update DT496 set CAN_DELETE = 1",
                                        "alter table DT496 add constraint DT496CAN_DELETE_NOT_NULL check(CAN_DELETE "
                                        "is not null)",
                                        "alter table DT497 add CAN_DELETE number(5,0) default 1",
                                        "update DT497 set CAN_DELETE = 1",
                                        "alter table DT497 add constraint DT497CAN_DELETE_NOT_NULL check(CAN_DELETE "
                                        "is not null)",
                                        "alter table DT498 add CAN_DELETE number(5,0) default 1",
                                        "update DT498 set CAN_DELETE = 0",
                                        "alter table DT498 add constraint DT498CAN_DELETE_NOT_NULL check(CAN_DELETE "
                                        "is not null)",
                                        "alter table DT499 add CAN_DELETE number(5,0) default 1",
                                        "update DT499 set CAN_DELETE = 0",
                                        "alter table DT499 add constraint DT499CAN_DELETE_NOT_NULL check(CAN_DELETE "
                                        "is not null)"),

                          DBMS_MSSQL: ("alter table DT496 add CAN_DELETE numeric(5,0) default 1",
                                       "update DT496 set CAN_DELETE = 1",
                                       "alter table DT496 add constraint DT496CAN_DELETE_NOT_NULL check([CAN_DELETE] "
                                       "is not null)",
                                       "alter table DT497 add CAN_DELETE numeric(5,0) default 1",
                                       "update DT497 set CAN_DELETE = 1",
                                       "alter table DT497 add constraint DT497CAN_DELETE_NOT_NULL check([CAN_DELETE] "
                                       "is not null)",
                                       "alter table DT498 add CAN_DELETE numeric(5,0) default 1",
                                       "update DT498 set CAN_DELETE = 0",
                                       "alter table DT498 add constraint DT498CAN_DELETE_NOT_NULL check([CAN_DELETE] "
                                       "is not null)",
                                       "alter table DT499 add CAN_DELETE numeric(5,0) default 1",
                                       "update DT499 set CAN_DELETE = 0",
                                       "alter table DT499 add constraint DT499CAN_DELETE_NOT_NULL check([CAN_DELETE] "
                                       "is not null)")}


class A_AddProcessDeletionFlagSchema(SQLPacket):
    """Port the process deletion schema changes"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13737

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

    def fix(self, runner):
        for statement in ALTER_TABLE_STATEMENTS[ppms.db_get_dbms_name()]:
            self.modify_and_log(statement)

        return self.success()


class B_AddProcessDeletionFlagCustomizing(SQLPacket):
    """Port the process deletion flag DataItem"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13737

    FILENAME = 'wi13737_deletion_flag.sql'
    __PATH = r'migration.hotfix.S_39_5_13.wi13737_process_model_deletion_flag.A_AddProcessDeletionFlagSchema'

    def get_dependencies(self):
        return (MinVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING),
                MaxVersionDependency(version='39.5', version_type=VersionType.CUSTOMIZING),
                PacketDependency(packet_path=self.__PATH, expected_state=PacketState.INSTALLED))

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

        return self.success()


OLD_CODE = """from ppms import ppms_cu
from ppms import processes

# Moduldaten
mod_obj=ppms.get_target_module()

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

if inv_rec.get_dtp_record().__getattr__("step_class").get_value() == 0 and inv_rec.get_dtp_record().__getattr__("step_id_default_model").get_value() != "":
    ppms.ui_message_id("0784")

elif inv_rec.get_dtp_record().parent_step_id.get_value() != "" or inv_rec.get_dtp_record().__getattr__("step_class").get_value() == 0:

    ppms.echo_off()
    inv_rec.get_da().get_customizing().set_permission_delete()
    inv_rec.mark()
    mod_obj.menu(34)
    mod_obj.menu(40)
    inv_rec.get_da().get_customizing().unset_permission_delete()
    ppms.echo_on()

else:
    ppms.ui_message_id("0772")"""
SUBCLASS_PATH = 'ppms.module_subclasses.processes.DeleteProcessStepMacro'


class C_ReplaceProcessStepDeletionMacro(ChangeDTPPacket):
    """Replace the old process step deletion macro with the new subclass"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13737

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

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

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

        return self.success()


class D_ChangeFuturePhaseDeletion(ChangeDTPPacket):
    """Add the new deletion logic to the future steps dataarea"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13737

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

    def fix(self, runner):
        da_id = 339367
        record = self.get_record(dt_num=406, key_list=[da_id], di_list=['delete_enabled'])
        if not self.change_value(record=record, attribute='delete_enabled', old_value=1, new_value=0):
            return self.fail('Could not change customizing')

        return self.success()