# -*- coding: utf-8 -*-

from ppms.migration.packet import *

class FixValueRange001517(ChangeDTPPacket):
    '''Fix wrong DI in value range of DI001517.'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 10363

    def fix(self, runner):
        OLD_VAL = """from ppms import ppms_cu

def processInput(di, oldvalue):
    rec = di.get_dtp_record()
    res_id=di.get_value()
    
    if res_id is None or res_id in ["","-"]:       
        return ""
    else:
        mapping=[]
        mapping.append(["def_cost_type","ct_id"])

        rec467=ppms.search_record(467, [res_id], [1218,2499,804,803,830,1237,1283], True)
        if not rec467:
            message=ppms_cu.Helper.get_const_title("001247")
            ppms.ui_message_box(message.replace("@user_id",res_id))
            return ""
        else:
            if rec467.res_to_be_planed.get_value() == 1:
                for entry in mapping:
                    try:
                        rec.__getattr__(entry[1]).set_string_value(str(rec467.__getattr__(entry[0]).get_value()))
                    except:
                        pass
                return di.get_value()
            else:
                ppms.ui_message_id("1039")
                return ""
    
processInput.deps = ("DI001467",)"""

        NEW_VAL = """from ppms import ppms_cu
from ppms.exits import project_exits

def processInput(di, oldvalue):
    rec = di.get_dtp_record()
    if 'lock_rec' in ppms_cu.Access.get_ppms_builtins("ppms").keys():
        auto_var = ppms_cu.Access.get_ppms_builtins("ppms")['lock_rec']
    else:
        auto_var = None    
    if auto_var:
        return di.get_value()
    else:
        rec = di.get_dtp_record()
        res_id = di.get_value()
        task_id = rec.task_id.get_value()
        pr_id = rec.pr_id.get_value()
        cost_type = ""
        
        if res_id:
            rec467 = ppms.search_record(467, [res_id], [830], True)
            
            if rec467: 
                cost_type = rec467.def_cost_type.get_value()
                
        if res_id and task_id and pr_id:
            rec466 = ppms.search_record(466, [pr_id, task_id, res_id], [1393], True)

            if rec466:
                cost_type = rec466.cost_type.get_value()
            
        cost_set = rec.ct_id.set_value(cost_type)
            
        if res_id is None or res_id in ["","-"]:       
            return ""
        else:
            return res_id
    
processInput.deps = ("DI001395","DI001516","DI001517","DI001518")"""

        record = self.get_record(412, ['001517'], [27352])
        if not self.change_value(record, 'valuerange', OLD_VAL, NEW_VAL):
            return self.fail()

        return self.success()
