"""
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)
    
    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
    
    """
    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_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 suffix_pv.__contains__(str(buff_num)):
                    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]]
    """
    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_spacing_count(bpm_dict, buff_to_count):
    """
    Adds a count of the given 
    """
    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:
                    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
    """
    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 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
    
def add_bpm(bpm_dict, bpm, buff_num):
    """
    Adds the given bpm and bsa buffer number to the bpm_dict
    """
    bpm_dict[bpm]={}
    bpm_dict[bpm][buff_num]={}
    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_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')
    """
