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


"""


from epics import caget, caget_many #, caput, PV
import sys
import os
import time
import subprocess
from pathlib import Path
import argparse
import datetime
import glob
import numpy
import json

IOC_DATA = os.environ.get('IOC_DATA')
PATTERN_TOP = os.path.join(IOC_DATA, 'sioc-sys0-ts01/TpgPatternSetup')
tod = datetime.datetime.now()
tod_list = str(tod).split(" ")
date = tod_list[0]
REPORT_TOP = os.path.join(PATTERN_TOP, "reports")
REPORT_DATE = os.path.join(REPORT_TOP, date)
print(f'saving reports to: REPORT_DATE')
if not os.path.exists(REPORT_DATE):
    os.mkdir(REPORT_DATE)
    

def get_bpm_bsa_data(bpm_dict, 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'{bpm}:{suffix}{buff_num}')
             
    suffix_values = caget_many(suffix_pvs)
    #print(suffix_values)
    
    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
        #print(index)
        #print(type(index))
        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
    
    """
    bpm_bsa_data['TMITPIDHST'] = caget(f'{bpm}:TMITPIDHST{buff_num}')
    bpm_TMITPIDHST_diff=[]
    for index, entry in enumerate(bpm_TMITPIDHST):
        if index > 0:
            bpm_TMITPIDHST_diff.append(entry - bpm_TMITPIDHST[index-1])   
    """ 
    
    
def save_data(bpm_dict, filepath):
    """
    Saves the data from the bpm_dict in a 
    """
    
    bpm_json = json.dumps(bpm_dict, indent=4)
    
    try:
        with open(filepath, "w") as json_file:
            json_file.write(bpm_json)
            
    except:
        print("can't write json")
        
        
def get_pid_variation(bpm_dict):
    """
    make a dictionary of how much variation there is between difference of beam
    pulses
    """
    pid_variation={}
    for bpm in bpm_dict:
        for buff_num in bpm_dict[bpm]:
            for index, pid in enumerate(bpm_dict[bpm][buff_num]['TMITPIDHST']):
                if index > 0:
                    pid_diff = pid - bpm_dict[bpm][buff_num]['TMITPIDHST'][index-1]
                    if pid_diff not in pid_variation:
                        pid_variation[pid_diff] = 1
                    else:
                        pid_variation[pid_diff] = pid_variation[pid_diff]+1
            bpm_dict[bpm][buff_num]['pid_variation'] = pid_variation
            pid_variation={}
    return bpm_dict

def check_tmit(bpm_dict):
    """
    """
    
    for bpm in bpm_dict:
        for buff_num in bpm_dict[bpm]:
            n_good_tmit=0
            for tmit in bpm_dict[bpm][buff_num]['TMITHST']:
                if tmit > 10e7:
                    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
    return bpm_dict
    
    
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')
    
    json_file_path =  os.path.join(PATTERN_TOP, "reports/test.json")
    
    save_data(bpm_dict, json_file_path)
    

    bpm_dict = get_pid_variation(bpm_dict)

    print (bpm_dict)

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