import os
import json
import subprocess
from collections import defaultdict
from functools import partial
import epics
import time
import numpy as np
import pprint
import math
import argparse
import sys

tpr_list =['TPR:BSYH:BP01:0',
'TPR:BSYH:BP02:0',
'TPR:BSYH:BP03:0',
'TPR:BSYS:BP01:0',
'TPR:DMPH:BP01:0',
'TPR:DMPH:BP02:0',
'TPR:DMPS:BP01:0',
'TPR:DMPS:BP02:0',
'TPR:LTUH:BP01:0',
'TPR:LTUH:BP02:0',
'TPR:LTUH:BP03:0',
'TPR:LTUH:BP04:0',
'TPR:LTUH:BP05:0',
'TPR:LTUH:BP06:0',
'TPR:LTUH:BP07:0',
'TPR:LTUH:BP08:0',
'TPR:LTUH:BP09:0',
'TPR:LTUH:BP10:0',
'TPR:LTUH:BP11:0',
'TPR:LTUH:BP13:0',
'TPR:LTUH:BP15:0',
'TPR:LTUS:BP01:0',
'TPR:LTUS:BP03:0',
'TPR:LTUS:BP04:0',
'TPR:LTUS:BP05:0',
'TPR:LTUS:BP06:0',
'TPR:LTUS:BP07:0',
'TPR:LTUS:BP08:0',
'TPR:LTUS:BP09:0',
'TPR:LTUS:BP10:0',
'TPR:LTUS:BP11:0',
'TPR:LTUS:BP12:0',
'TPR:LTUS:BP14:0',
'TPR:LTUS:BP16:0',
'TPR:LTUS:BP17:0',
'TPR:UNDH:BP01:0',
'TPR:UNDH:BP02:0',
'TPR:UNDH:BP03:0',
'TPR:UNDH:BP04:0',
'TPR:UNDH:BP05:0',
'TPR:UNDH:BP06:0',
'TPR:UNDH:BP07:0',
'TPR:UNDH:BP08:0',
'TPR:UNDH:BP09:0',
'TPR:UNDH:BP10:0',
'TPR:UNDH:BP11:0',
'TPR:UNDH:BP12:0',
'TPR:UNDH:BP13:0',
'TPR:UNDH:BP14:0',
'TPR:UNDH:BP15:0',
'TPR:UNDH:BP16:0',
'TPR:UNDH:BP17:0',
'TPR:UNDH:BP18:0',
'TPR:UNDH:BP19:0',
'TPR:UNDH:BP20:0',
'TPR:UNDS:BP01:0',
'TPR:UNDS:BP02:0',
'TPR:UNDS:BP03:0',
'TPR:UNDS:BP04:0',
'TPR:UNDS:BP05:0',
'TPR:UNDS:BP06:0',
'TPR:UNDS:BP07:0',
'TPR:UNDS:BP08:0',
'TPR:UNDS:BP09:0',
'TPR:UNDS:BP10:0',
'TPR:UNDS:BP11:0',
'TPR:UNDS:BP12:0',
'TPR:UNDS:BP13:0',
'TPR:UNDS:BP14:0',
'TPR:UNDS:BP15:0']



if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='This program is a tool for setting the MSGDLYS for TPRs in the hard and soft lines, usage: python bpm_triggering.py -W  or bpm_triggering.py -b H -W' ) 
    parser.add_argument('-b' ,'--beamline', choices=['H','S'],default = 'S')
    parser.add_argument('-W', '--write_values',action = 'store_true', help = 'Tells the software to put to the selected TPR PVs')
    parser.add_argument('-v', '--values', action= 'store_true', help = 'Shows the values used in the TPR MSGDLY calculation')
    args = parser.parse_args()
    
    get_tref_list = []
    get_msgdly_list = []
    deltas = {}
    msgdlys = {}
    trefs = {}
    ## if S use BSYS:BP01, if H use LTUH:BP01 as  ref for all devs in tpr_list at the top
    if args.beamline == 'S':
        ref_tpr = 'TPR:BSYS:BP01:0'

    elif args.beamline == 'H':
        ref_tpr = 'TPR:LTUH:BP01:0'

    get_tref_list.append(ref_tpr+':TREF')
    
    for dev in tpr_list:
        if dev != ref_tpr:
            get_tref_list.append(dev+':TREF')

    #print(get_tref_list)
    ref_dev_msgdly = epics.caget(ref_tpr+':MSGDLY')

    got_tref_list = epics.caget_many(get_tref_list,timeout=1)
    got_msgdly_list = epics.caget_many(get_msgdly_list,timeout=1)
    for i in range(len(got_tref_list)):
        if got_tref_list[i] is not None:
            ## delta val = tref - ref_dev_tref
            temp = got_tref_list[i]-got_tref_list[0]
            dev = get_tref_list[i].rsplit(':',1)[0]
            deltas[dev] = temp
            trefs[get_tref_list[i]]=got_tref_list[i]
        else:
            print(get_tref_list[i], ' is none')

    if args.values:
        print('\n')
        print('TREFS DICTIONARY')
        print('TREFS DICTIONARY')
        
        pprint.pprint(trefs)
        print('\n')
        print('DELTAS DICTIONARY')
        print('DELTAS DICTIONARY')
    
        pprint.pprint(deltas)
        print('\n')
        #pprint.pprint(msgdlys)
        print('REF DEVICE MSGDLY')
        print('REF DEVICE MSGDLY')
        
        print(ref_tpr+ ':MSGDLY', ' ',ref_dev_msgdly)
        print('\n')
    trigger = {}
    keys = list(deltas.keys())
    for key in keys:
        msg_key = key + ':MSGDLY'
        #trigger val =  delta val + ref dev msgdly
        trigger[msg_key] = deltas[key] + ref_dev_msgdly


    print('TRIGGER DICTIONARY')
    print('TRIGGER DICTIONARY')
    pprint.pprint(trigger)
    print('\n')
    error_flag = False
    for key in list(trefs.keys()):
        tkey = key.rsplit(':',1)[0] +  ':MSGDLY'
        d1 =trigger[tkey] - ref_dev_msgdly
        d2 = trefs[key]-got_tref_list[0]
        if d2 != d1:
            print(d1, ' ', d2)
            print('problem at :', key)
            error_flag = True
    if error_flag == True:
        print('Sanity check failed, exiting program without caputting')
        sys.exit(0)
    elif error_flag == False:
        put_devs = list(trigger.keys())
        put_vals = list(trigger.values())
        items = list(trigger.items())

        for i in range(len(items)):
            if put_devs[i] != items[i][0] or put_vals[i] != items[i][1]:
                print('error')
                sys.exit(0)

        if args.write_values:

            '''
            print('Caputting new MSGDLY values')
            put_list = epics.caput_many(put_devs,put_vals)
            for i in range(len(put_devs)):
                if put_list[i] == 1:
                    print(put_devs[i],' was caput successfully')
                elif put_list[i] == -1:
                    print(put_devs[i],' has failed to be caput')
            '''
        else:
            print('Printing caput commands. Not caputting to PVs')
            for i in range(len(items)):
                print('caput %s %i' % (put_devs[i], put_vals[i]))
