import os
import sys
import argparse
import json
import datetime
import requests
import time
import re
import pprint
import glob
import csv
import epics
from datetime import datetime



if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='This program is a tool for getting/putting IOC, BPM, and TPR values. In addition, there is also functionality built-in for rebooting (-R) or upgrading the Firmware (-F) for IOCs.  Devices are individually searchable or searchable by Linac locations or specialties (-l NC SC COMMON HARD SOFT CAVITY). sample usage '"python bpmTool.py -d ioc -l HTR -v STARTTOD "'' ) 
    parser.add_argument('-o' ,'--offset', help = "Specifies the value to offset the current TPR msgdelay pv by")
    parser.add_argument('-z' ,'--zone', help = "Specifies IOCS by zone")
    args = parser.parse_args()
    print(args)

    zone_one = ['SIOC:L2B:BP07','SIOC:BC2B:BP01','SIOC:BC2B:BP02','SIOC:EMIT2:BP01','SIOC:L3B:BP01',
                'SIOC:L3B:BP02','SIOC:L3B:BP03','SIOC:L3B:BP04','SIOC:L3B:BP05','SIOC:L3B:BP06','SIOC:L3B:BP07',
                'SIOC:L3B:BP08','SIOC:L3B:BP09','SIOC:L3B:BP10','SIOC:L3B:BP11','SIOC:EXT:BP01','SIOC:DOG:BP01',
                'SIOC:DOG:BP02','SIOC:DOG:BP03','SIOC:DOG:BP04','SIOC:DOG:BP05','SIOC:DOG:BP06','SIOC:DOG:BP07',
                'SIOC:DOG:BP08','SIOC:DOG:BP09','SIOC:DOG:BP10','SIOC:BPN13:BP01','SIOC:BPN14:BP01',
                'SIOC:BPN15:BP01','SIOC:BPN16:BP01','SIOC:BPN17:BP01','SIOC:BPN18:BP01','SIOC:BPN19:BP01','SIOC:BPN20:BP01',
                'SIOC:BPN21:BP01','SIOC:BPN22:BP01','SIOC:BPN23:BP01','SIOC:BPN24:BP01','SIOC:BPN25:BP01','SIOC:BPN26:BP01','SIOC:BPN27:BP01']
    
    zone_two = ['SIOC:BPN28:BP01','SIOC:SPD:BP01', 'SIOC:SPD:BP02', 'SIOC:SPD:BP03', 'SIOC:SPD:BP04', 'SIOC:SPD:BP05' ]

    zone_three = ['SIOC:SLTD:BP01']
    if args.zone == 'z1':
        iocs =zone_one
    elif args.zone == 'z2':
        iocs = zone_two
    elif args.zone == 'z3':
        iocs = zone_three


    tprs_msg_delay= []
    for ioc in iocs:
        ioc = ioc.split(':',1)
        tpr = 'TPR:' + ioc[1] + ':0:MSGDLY'
        #print(tpr)
        tprs_msg_delay.append(tpr)


    got = epics.caget_many(tprs_msg_delay)
    used_tprs = []
    used_got = []
    new_vals = []
    for i in range(len(tprs_msg_delay)):
        if got[i] is not None:
            #print(tprs_msg_delay[i], ' ', got[i])
            used_tprs.append(tprs_msg_delay[i])
            used_got.append(got[i])
            temp_val = float(args.offset) + float(got[i])
            new_vals.append(temp_val)
        #temp_value = float(args.offset) + float(got[i])
        #new_vals.append(temp_value)
    for i in range(len(used_tprs)):
        print('caputting ', used_tprs[i], ': ',new_vals[i], '    ', used_got[i] )

    #put = epics.caget_many(tprs_msg_delay, new_vals)
    #print(put)