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


class AddNewDataFieldToProcessModelCopy(SQLPacket):
    """Add a new data field to be filled when copying process steps"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13727

    __PATH = r'migration.hotfix.S_39_5_13.wi13721_process_model.B_PortProcessModelDataitems'
    FILENAME = 'wi13727_fix_process_phase_display.sql'

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

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

        return self.success()

OLD_CODE = """def computeOutput(di):
    dtpRec = di.get_dtp_record()
    pm_model = dtpRec.pm_model.get_value()
    pr_id = dtpRec.pr_id.get_value()

    if pm_model != "":
        sel_498=ppms.db_select(ppms.get_query("000219").format(pr_id ))

        phase_dic={}
        phase_list=[]

        for rec in sel_498:
            for ident in rec:
                str(ident)
                rec498=ppms.search_record(497, [ident], [41194], True)
                rec498=rec498.title.get_value()
                phase_list.append([ident,rec498])
    else:
        phase_list=[['1', '']]

    return str(phase_list)

computeOutput.deps = ('DI001001','DI041200','*')"""
NEW_CODE = '''OLD_QUERY = """Select di041152 from DT499 WHERE DI057817='{0}' GROUP BY di041152, di041163, di041187 ORDER BY di041163, di041187 DESC"""

def computeOutput(di):
    dtpRec = di.get_dtp_record()
    pm_model = dtpRec.pm_model.get_value()
    pr_id = dtpRec.pr_id.get_value()

    if pm_model != "":
        sel_498=ppms.db_select(ppms.get_query("000219").format(pr_id,pm_model))

        phase_dic={}
        phase_list=[]

        if not sel_498:
            sel_498 = ppms.db_select(OLD_QUERY.format(pr_id))

        for rec in sel_498:
            for ident in rec:
                str(ident)
                rec498=ppms.search_record(497, [ident], [41194], True)
                rec498=rec498.title.get_value()
                phase_list.append([ident,rec498])
    else:
        phase_list=[['1', '']]

    return str(phase_list)

computeOutput.deps = ('DI001001','DI041200','*')'''


class ChangeProcessModelValuerange(ChangeDTPPacket):
    """Change a value range in the process model to correct the phase display"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13727

    __PATH = r'migration.hotfix.S_39_5_13.wi13721_process_model.B_PortProcessModelDataitems'

    def get_dependencies(self):
        return (PacketDependency(packet_path=self.__PATH, expected_state=PacketState.INSTALLED),
                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=412, key_list=['041204'], di_list=['valuerange'])
        if not self.change_value(record=record, attribute='valuerange', old_value=OLD_CODE, new_value=NEW_CODE):
            return self.fail('Could not change valuerange. Individual customizing?')

        return self.success()


OLD_QUERY = """Select di041152 from DT499 WHERE DI057817='{0}' GROUP BY di041152, di041163, di041187 ORDER BY di041163, di041187 DESC"""
NEW_QUERY = """Select di041152 from DT499 WHERE DI057817='{0}' AND DI061407 = '{1}' AND DI058037 <> '218' GROUP BY di041152, di041163, di041187 ORDER BY di041163, di041187 DESC"""


class ChangeProcessModelQuery(ChangeDTPPacket):
    """Change a valuerange in the process model to correct the phase display"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13727

    __PATH = r'migration.hotfix.S_39_5_13.wi13721_process_model.B_PortProcessModelDataitems'

    def get_dependencies(self):
        return (PacketDependency(packet_path=self.__PATH, expected_state=PacketState.INSTALLED),
                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=343, key_list=['-', '000219'], di_list=['source_text_clob'])
        if not self.change_value(record=record, attribute='source_text_clob', old_value=OLD_QUERY, new_value=NEW_QUERY):
            return self.fail('Could not change query. Individual customizing?')

        return self.success()
