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


OLD_VALUE = """def processInput(di, oldvalue):
    rec = di.get_dtp_record()
    
    if len(rec.resource_type.get_value()) > 0 and di.get_value() != 0:
        if rec.resource_type.get_value()[0] == "1":
            rec516=ppms.search_record(516, [di.get_value()], [10420], True)
            if rec516 != None:
                name=rec516.name_full.get_value()           
                rec.title.set_string_value(name)
                return di.get_value()
            else:
                ppms.ui_message_id("0686")
                return oldvalue
        else:
            ppms.ui_message_id("0052")
            
            return 0
    else:
        return 0
        
processInput.deps=("DI003414","DI001275")"""

NEW_VALUE = """def processInput(di, oldvalue):
    rec = di.get_dtp_record()

    if len(rec.resource_type.get_value()) > 0 and di.get_value() != 0:
        if rec.resource_type.get_value()[0] == "1":
            rec516=ppms.search_record(516, [di.get_value()], [10420, 27357], True)
            if rec516 != None:
                name=rec516.name_full.get_value()
                rec.title.set_string_value(name)
                return di.get_value()
            else:
                ppms.ui_message_id("0686")
                return oldvalue
        else:
            ppms.ui_message_id("0052")

            return 0
    else:
        return 0

processInput.deps=("DI003414","DI001275")"""


class FixDT516ValueRange(ChangeDTPPacket):
    """Correct the valuerange of DI 040609

    The line

    rec516=ppms.search_record(516, [di.get_value()], [10420], True)

    gets replaced with

    rec516=ppms.search_record(516, [di.get_value()], [10420, 27357], True)
    """
    version = 1
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13006

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

    def fix(self, runner):
        record = self.get_record(dt_num=412, key_list=['040609'], di_list=['valuerange'])

        if not self.change_value(record=record, attribute='valuerange', old_value=OLD_VALUE, new_value=NEW_VALUE):
            return self.fail('Could not change the valuerange, maybe there was a individual customizing')

        return self.success()