"""
Pattern verification script
Verifies the spacing in a pattern using bsa


"""


from epics import caget, caget_many
import functools
 

def get_bpm_bsa_data(bpm_dict, suffix):
    """
    gets the bpm bsa data for the given suffix, i.e. TMITHST
    If speed really ends up being a problem can re-write and merge the caget_many
    Probably not the best idea though for safety
    
    input
    ------
   	bpm_dict:
   	    A dictionary with the following structure
   	    bpm_dict[bpm][buff_num]={}
   	    This supports multiple bpms across multiple buffers
    suffix:
        bsa suffix for the bpms, ie TMITHST

   	output
   	------
   	bpm_dict:
        Dictionary of the bpm BSA data with the following keys
    
            bpm_dict[bpm][buff_num][suffix]:
    """
    suffix_pvs=[]
    for bpm in bpm_dict:
        for buff_num in bpm_dict[bpm]:
             suffix_pvs.append(f'{bpm}:{suffix}{buff_num}')
    suffix_values = caget_many(suffix_pvs)
    
    for index, suffix_pv in enumerate(suffix_pvs):
        split_suffix = suffix_pv.split(f':{suffix}')
        bpm = split_suffix[0]
        buff_num = int(split_suffix[1])
        #don't need decimals and need a pythonic list to wrap into json format
        try:
            bpm_dict[bpm][buff_num][suffix] = [int(i) for i in suffix_values[index].tolist()]
        except:
            print("do not need to convert list to ints")
            bpm_dict[bpm][buff_num][suffix] = list(suffix_values[index])

    return bpm_dict
    
        
def get_tpg_bsa_data(bpm_dict, tpg_base, suffix):
    """
    If speed really ends up being a problem can re-write and merge the caget_many
    Probably not the best idea though for safety
    
    input
    ------
   	bpm_dict:
   	    A dictionary with the following structure
   	    bpm_dict[bpm][buff_num]={}
   	    This supports multiple bpms across multiple buffers

   	output
   	------
   	bpm_dict:
        Dictionary of the bpm BSA data with the following keys
    
            bpm_dict[bpm][buff_num][suffix]:
    """
    
    suffix_pvs=[]
    for bpm in bpm_dict:
        for buff_num in bpm_dict[bpm]:
             suffix_pvs.append(f'{tpg_base}:{suffix}{buff_num}')
    suffix_values = caget_many(suffix_pvs)
    
    for bpm in bpm_dict:
        for buff_num in bpm_dict[bpm]:
            for index, suffix_pv in enumerate(suffix_pvs):
                if not suffix_pv.__contains__(str(buff_num)):
                    continue
                bpm_dict[bpm][buff_num][suffix] = [int(i) for i in suffix_values[index].tolist()]
                if suffix == 'BEAMREQHST':
                    bpm_dict[bpm][buff_num][suffix] = [hex(i) for i in bpm_dict[bpm][buff_num][suffix]]

    return bpm_dict
        
def get_spacing_count(bpm_dict, buff_to_count):
    """
    Adds a count of the spacing of the values in a given buffer
    ie
    bpm_dict[bpm][buff_num][buff_to_count] = [1,2,3,5] 
    returns
    bpm_dict[bpm][buff_num][f'{buff_to_count}_spacing_count'] = {"1":2, "2":1}
    """
    spacing_count={}
    for bpm in bpm_dict:
        for buff_num in bpm_dict[bpm]:
        
            #check len at some point
        
            for index, entry in enumerate(bpm_dict[bpm][buff_num][buff_to_count]):
                if index == 0:
                    continue
                diff = entry - bpm_dict[bpm][buff_num][buff_to_count][index-1]
                if diff not in spacing_count:
                    spacing_count[diff] = 1
                else:
                    spacing_count[diff] = spacing_count[diff]+1
                        
            bpm_dict[bpm][buff_num][f'{buff_to_count}_spacing_count'] = spacing_count
            spacing_count={}
    return bpm_dict
    
def get_count(bpm_dict, buff_to_count):
    """
    Addes a count of the given buffer to the bpm_dict
    ie
    bpm_dict[bpm][buff_num][buff_to_count] = [1,1,3,5] 
    returns
    bpm_dict[bpm][buff_num][f'{buff_to_count}_spacing_count'] = {"1":2, "3":1, "5":1}
    """
    count={}
    for bpm in bpm_dict:
        for buff_num in bpm_dict[bpm]:
        
            #check len at some point
        
            for index, entry in enumerate(bpm_dict[bpm][buff_num][buff_to_count]):
                if entry not in count:
                    count[entry] = 1
                else:
                    count[entry] = count[entry]+1
                        
            bpm_dict[bpm][buff_num][f'{buff_to_count}_count'] = count
            count={}
    return bpm_dict


def for_every_bpm(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        bpm_dict = args[0]
        for bpm in bpm_dict:
            for buff_num in bpm_dict[bpm]:
                bpm_dict = func(bpm_dict, bpm, buff_num, **kwargs) 
        return bpm_dict
    return wrapper


def for_every_bpm_check(func):
    """
    Wrapper that allows for checks
    Functions that use this wrapper must return an array of the following from
    [bpm_dict, check_result_0, check_result_1, check_result_2, ...]
    where bpm_dict is the bpm dictionary with any edits
    and the check_result_X are bools
    This wrapper will make sure each check is true for each bpm in bpm_dict
    """
    @functools.wraps(func)
    def wrapper(*args):
        bpm_dict = args[0]
        all_bpm_check = []
        first_pass = True
        for bpm in bpm_dict:
            for buff_num in bpm_dict[bpm]:
                func_output = func(bpm_dict, bpm, buff_num)
                bpm_dict = func_output[0]
                checks = func_output[1:]
                for check_idx, check in enumerate(checks):
                    if first_pass:
                        all_bpm_check.append(check)
                        pass
                    if not check:
                        all_bpm_check[check_idx] = check

                first_pass = False
                print(f"all_bpm_check: {all_bpm_check}")

        return bpm_dict, all_bpm_check
    return wrapper

@for_every_bpm_check
def check_tmit(bpm_dict, bpm, buff_num):
    """
    Decorated, so only argument needed is 
    Checks that the TMITHST > 10e7 for each bpm in bpm_dict
    adds n_pulses and n_good_tmit
    """
    has_good_tmit = True
    n_good_tmit=0
    for tmit in bpm_dict[bpm][buff_num]['TMITHST']:
        if tmit > 10e7 and bpm_dict[bpm][buff_num]['tmit_required']:
            n_good_tmit = n_good_tmit+1
        if tmit < 10e7 and not bpm_dict[bpm][buff_num]['tmit_required']:
            n_good_tmit = n_good_tmit+1

    bpm_dict[bpm][buff_num]['n_pulses'] = len(bpm_dict[bpm][buff_num]['TMITHST'])
    bpm_dict[bpm][buff_num]['n_good_tmit'] = n_good_tmit
    if n_good_tmit != len(bpm_dict[bpm][buff_num]['TMITHST']):
        has_good_tmit = False

    return bpm_dict, has_good_tmit
    
def add_bpm(bpm_dict, bpm, buff_num, tmit_required):
    """
    Adds the given bpm and bsa buffer number to the bpm_dict
    Adds tmit_required flag (checks for tmit > 10e7) if set to true
    """
    bpm_dict[bpm]={}
    bpm_dict[bpm][buff_num]={}
    bpm_dict[bpm][buff_num]['tmit_required'] = tmit_required
    is_bpm_online = caget(f'{bpm}:TMIT')
    if is_bpm_online == None:
        print(f'{bpm} is offline')
    return bpm_dict

@for_every_bpm
def write_info(bpm_dict, bpm, buff_num, **kwargs):
    """
    Writes info for the bpm in the bpm dict
    """
    bpm_dict[bpm][buff_num]['info'] = [
    f'---------------',
    f'bpm: {bpm}, buffer: {buff_num}',
    f'bpm pid spacing count',
    f'{bpm_dict[bpm][buff_num]["TMITPIDHST_spacing_count"]}',
    f'tpg pid spacing count',
    f'{bpm_dict[bpm][buff_num]["PIDLHST_spacing_count"]}',

    f'BSSS pid spacing count',
    f'{bpm_dict[bpm][buff_num]["BSSS_TMITPID_spacing_count"]}',
    f'BSSS pid points aquired',
    f'{len(bpm_dict[bpm][buff_num]["BSSS_TMITPID"])}',
    f'BSSS tmit points aquired',
    f'{len(bpm_dict[bpm][buff_num]["BSSS_TMIT"])}',

    f'all BSSS pid in BSA',
    f'{bpm_dict[bpm][buff_num]["all_BSSS_PID_in_BSA"]}',
    f'all BSSS tmit match BSA tmit on pid',
    f'{bpm_dict[bpm][buff_num]["BSSS_TMIT_match_BSA_on_PID"]}',

    f'TMIT above 10e7 required: {bpm_dict[bpm][buff_num]["tmit_required"]}',
    f'Pulses with beam, checked by tmit: {bpm_dict[bpm][buff_num]["n_good_tmit"]}',
    f'Total pulses: {bpm_dict[bpm][buff_num]["n_pulses"]}',
    f'BEAMREQHST',
    f'{bpm_dict[bpm][buff_num]["BEAMREQHST_count"]}',
    ]
    return(bpm_dict)


def get_info(bpm_dict):
    """
    returns all the info for the bpms in one string
    """
    info = ""
    for bpm in bpm_dict:
        for buff_num in bpm_dict[bpm]:
            for string in bpm_dict[bpm][buff_num]['info']:
                    info = info + string + "\n"
    return info

    
if __name__=="__main__":
    #test to make sure these functions work
    bpm_list = []
    buff_num_list = []
    """bpm_dict = {'BPMS:SLTD:895':{'39':{},'42':{}},
                'BPMS:HTR:960':{'41':{}},
    }"""
    bpm_dict = {'BPMS:BSYH:445':{'39':{},'42':{}},
                'BPMS:HTR:960':{'41':{}},
    }
    bpm_dict = get_bpm_bsa_data(bpm_dict, 'TMITPIDHST')
    bpm_dict = get_bpm_bsa_data(bpm_dict, 'TMITHST')
   
    
    bpm_dict = get_spacing_count(bpm_dict)

    print (bpm_dict)

    """
    check_bpm('BPMS:SLTD:895','39')
    check_bpm('BPMS:HTR:960','41')
    check_bpm('BPMS:SLTD:895','42')
    """
