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

from ppms.migration import ChangeDTPPacket, PacketCategory, MinVersionDependency, MaxVersionDependency, VersionType


class FixDepartmentAbsenceFilter(ChangeDTPPacket):
    '''Fix filter criteria in MOD009ALC to show absence of other department members'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12367

    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):
        recs = ({'dt':405,
                 'pk':['009ALC'],
                 'di':['py_macro_text'],
                 'old_val':'''def show_resource(res_id):
    if type(res_id)==str:
        mod_obj.set_current_L_var(5, [res_id])
    else:
        mod_obj.set_current_L_var(5, res_id)
    
    mod_obj.menu(19)

mod_obj=ppms.get_target_module()

def on_load():
    mod_obj.show_resource=show_resource
    
def on_initial_focus():
    on_load()
    mod_obj.menu(12)
    
def on_focus():
    pass
    
def on_reset():  
    mod_obj.menu(12)''',
                 'new_val':'''def show_resource(res_id):
    if type(res_id)==str:
        mod_obj.set_current_L_var(5, [res_id])
    else:
        mod_obj.set_current_L_var(5, res_id)
    
    mod_obj.menu(19)

mod_obj=ppms.get_target_module()

def on_load():
    mod_obj.show_resource=show_resource

    cur_user = ppms.uvar_get('@1')

    parent = ppms.search_record(467, [cur_user], ['parent_res_id'], True).parent_res_id.get_value()

    if parent: 
        mod_obj.set_current_L_var(80, [parent])
    else:
        mod_obj.set_current_L_var(80, [cur_user])
    
def on_initial_focus():
    on_load()
    mod_obj.menu(12)
    
def on_focus():
    pass
    
def on_reset():  
    mod_obj.menu(12)'''},
                {'dt':411,
                 'pk':['050877', 729849],
                 'di':['filter_from'],
                 'old_val':'@32',
                 'new_val':''},
                {'dt':411,
                 'pk':['050877', 729851],
                 'di':['filter_from'],
                 'old_val':'',
                 'new_val':'@L80'})
        errors = 0

        for dict in recs:
            rec = self.get_record(dict['dt'], dict['pk'], dict['di'])
            if not self.change_value(rec, dict['di'][0], dict['old_val'], dict['new_val']):
                errors += 1
        
        if not errors:
            return self.success()
        return self.fail()