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

"""
ask about location parsing ie 
LCLSHOME Areas: (columns)
-------------------------------------------
Note: tab indicats the tab on the main display for that column, which includes multiple macihne areas.
GUNB
L0B  - Includes areas:  L0B, HTR, COL0
DIAG0
L1B  - Includes areas:  L1B, BC1B, COL1
L2B  - Includes areas:  L2B, BC2B, EMIT2          
L3B
EXT
DOG
BYP  - Includes sectors BPN13-28, on one page
SPR - (Spreader) 
Tab        Machine Areas
SPH        SPH
SPS        SPS
SPR-Dump   SPD, SLTD, BSYDUMP   (the same as BSY-Dump)
DASEL
IN20
LI21 thru LI30
BSY  (Bean Switch Yard) 
Tab        Machine Areas
BSY-Cu     CLTH, CLTS, BSYH and BSYS
BSY-SC     SLTH, SLTS, BSYH and BSYS
BSY- Dump  SPD, SLTD     (the same as SPR-Dump)
LTUH
LTUS
UNDH
UNDS
DMPH
DMPS
FEEH
FEES
NEH
XRT
FEH
"""
"""
ask about how to scrape all NC IOCs & BPMs

"""
"""
TEST EXTENSIONS
-d ioc -e STARTTOD 
-d bpm -e RCVR_POLL_PERIOD
-d bpm -e STA_ALH
-d tpr -e CH00_DESTMODE
"""

#####start by parsing master lists to get a list bpms ore ioc that fit the loca provided
class DevicesWithLocation():
    def __init__(self,devType:str= None,loca:list= None,devices:list = None)->None:
        self._deviceType = devType
        self._devices = devices
        self._loca = loca
        self._returnList = devices
        if self._loca:
            for i in range(len(self._loca)):
                #print(self._loca[i])
                if self._loca[i] == 'NC':
                    self._returnList = self.getNormalConducting(devList = self._returnList)
                elif self._loca[i] == 'SC':
                    self._returnList = self.getSuperConducting(devList = self._returnList )
                elif self._loca[i] == 'COMMON':
                    self._returnList = self.getCommon(devList = self._returnList )
                elif self._loca[i] == 'SOFT':
                    self._returnList = self.getSoftline(devList =  self._returnList)
                elif self._loca[i] == 'HARD':
                    self._returnList = self.getHardline(devList = self._returnList )
                elif self._loca[i] == 'CAVITY':
                    self._returnList = self.getCavity(devList = self._returnList )
                elif self._loca[i] == 'BYP':
                    self._returnList = self.getBypassline(devList = self._returnList )
                else: 
                    self._returnList = self.getByRegion(loc = self._loca[i], devList = self._returnList )
        else:
            self._returnList = self._devices

    def getNormalConducting(self,devList:list):
        temp = []
        for dev in devList:
            ts = dev.split(':',2)
            if ts[1] in ['IN20','LI21','LI22','LI23','LI24','LI25','LI26','LI27','LI28','LI29','LI30','CLTS','CLTH','BSY0']:
                temp.append(dev)
        return temp
    def getSuperConducting(self,devList:list):
        temp = []
        for dev in devList:
            ts = dev.split(':',2)
            if ts[1] in ['GUNB','L0B','DIAG0','HTR','COL0','L1B','BC1B','COL1',
                         'L2B','BC2B','EMIT2','L3B','EXT','DOG','SPR',
                         'SPS','SPH','SPD','SLTD','SLTH','SLTS'] or 'BPN' in ts[1]:
                temp.append(dev)
        return temp
    def getCommon(self,devList:list):
        temp = []
        for dev in devList:
            ts = dev.split(':',2)
            #print(ts)
            if ts[1] in ['BSYH','BSYS','DMPH','DMPS','LTUH','LTUS','UNDH','UNDS']:
                temp.append(dev)
        #print(temp)
        return temp
    def getByRegion(self,loc:str,devList:list):
        temp = []
        for dev in devList:
            ts = dev.split(':',2)
            if ts[1] == loc:
                temp.append(dev)
        return temp
    def getCavity(self,devList:list):
        temp = []
        for dev in devList:
            ts = dev.split(':',2)
            if ts[1] in ['UNDH','UNDS']:
                temp.append(dev)
        return temp
    def getHardline(self,devList:list):
        temp = []
        for dev in devList:
            ts = dev.split(':',2)
            if ts[1] in ['CLTH','BSYH','DMPH','LTUH','UNDH','SLTH','SPH']:
                temp.append(dev)
        return temp
    def getSoftline(self,devList:list):
        temp = []
        for dev in devList:
            ts = dev.split(':',2)
            if ts[1] in ['CLTS','BSYS','DMPS','LTUS','UNDS','SLTS','SPS']:
                temp.append(dev)
        return temp
    def getBypassline(self,devList:list):
        temp = []
        for dev in devList:
            ts = dev.split(':',2)
            #print(ts)
            if 'BPN' in ts[1]: 
                temp.append(dev)
        #print(temp)
        return temp
    def getDumpline(self,devList:list):
        pass
    def ReturnDevices(self):
        return self._returnList



class RebootIOCs():
    def __init__(self,devices:list = None,forceValue:bool = None)->None:
        self._devices = devices
        self._forceValue = forceValue
        self._promptForInvasiveAction(self._forceValue)
        if self._restartTrue:
            self._rebootIOCS(self._devices)


    def _promptForInvasiveAction(self,forceFlag):
        self._restartTrue = False
        if forceFlag:
            self._restartTrue = True
        else:
            print(self._devices)
            print("Are you sure you would like to restart these IOCS: yes/no?")
            restartOK = input()
            if  restartOK == 'yes':
                self._restartTrue = True


    def _rebootIOCS(self, deviceList:list = None):
        for dev in deviceList:
            dev = dev.lower()
            dev = dev.replace(':','-')
            ts = dev.split('-',2)
            if ts[0] in ['ioc','eioc']:
                print('Must reboot ', dev, ' another way.')
            else:
                #print('Restarting: ', dev)
                #print( 'sleep  1'  )
                cmd = 'sleep 1'
                mkstr = 'siocRestart ' + dev +' &'
                os.system(mkstr)
                os.system(cmd)
        else:
            pass 


    ## build in filter for VME crate IOCS
class UpdateFirmware():
    def __init__(self,devices:list = None,forceValue:bool=None,directory:str=None, script:str=None, mcsFile:str=None)->None:
        self._devices = devices
        self._forceValue = forceValue
        self._directory = directory
        self._script = script
        self._mcsFile = mcsFile 
        self._devPVDict = {}

        self._promptForInvasiveAction(self._forceValue)

        if self._restartTrue:
            self.printStatements(deviceList = self._devices)
            self.filterInvalids(pvs = self._devPVDict)
            self.upgradeFirmware(pvs = self._devPVDict)


    def _promptForInvasiveAction(self,forceFlag):
        self._restartTrue = False
        if forceFlag:
            self._restartTrue = True
        else:
            print(self._devices)
            print('Are you sure you want to upgrade the firware of these IOCS? yes/no')
            self.firmwareOK = input()
            if self.firmwareOK == 'yes':
                self._restartTrue = True

    def printStatements(self,deviceList:list):
        for devName in self._devices:
            ts = devName.split(':',2)
            if ts[0] == 'SIOC':
                temp = []
                crat = epics.caget(devName+':CRAT')
                if crat is not None:
                    shm = crat.lower()
                    shm = shm.replace(':','-')
                    shm = shm.replace('crat','shm')
                    temp.append(shm)
                    temp.append(epics.caget(devName+':SLOT'))
                    cpu = epics.caget(devName+':CPU')
                    cpu = cpu.replace(':','-')
                    cpu = cpu.lower()
                    temp.append(cpu)
                    key = devName.lower()
                    key = key.replace(':','-')
                    self._devPVDict[key] = temp
            elif ts[0] in ['IOC','EIOC']:
                print('Must upgrade the firmware for: ', devName, ' another way.')
        pprint.pprint(self._devPVDict)

    def filterInvalids(self,pvs:dict):
        for key in pvs.keys():
            if None in pvs[key]:
                del pvs[key]

    def upgradeFirmware(self,pvs:dict):
        for key in pvs.keys():
            mkstr = self._script + ' --shelfmanager ' + pvs[key][0] + ' --slot ' + str(pvs[key][1]) + ' --mcs ' + self._mcsFile + ' --cpu ' + pvs[key][2]
            #print(mkstr)
            now = datetime.now()
            dtStr =now.strftime("%Y%m%d_%H%M%S")
            #print('Placehold for writing to file: ' +self._directory+'/'+ key+'_fw_update_'+str(dtStr)+'.txt')
            fileStr = self._directory+'/'+ key+'_fwupdate_'+str(dtStr)+'.txt'
            os.system(mkstr + ' >' + fileStr +' &' )
            os.system('sleep 1')
            #os.system( 'caget SIOC:SLTS:BP02:STARTTOD > outputFiles/temp_'+str(dtStr)+'.txt')
            #os.system('sleep 1')




class PVValue():
    def __init__(self,extension,devices:list,hexi:bool,numericTrue:bool,forceValue:bool=None,putValue = None)->None:
        self._ext = extension
        self._putValue = putValue 
        self._forceValue = forceValue
        self._devices = devices
        self._hex = hexi
        self._numeric = numericTrue




    def getIOCPVs(self):
        getList = []
        for devName in self._devices:
            temp = devName +':' + self._ext
            #print(temp) 
            getList.append(temp)


        if self._numeric:
            gotList = epics.caget_many(getList)
        else:
            gotList = epics.caget_many(getList,as_string=True)


        for i in range(len(getList)):
            if gotList[i] is None:
                print('Channel connect timed out: ', getList[i],' not found.' )
            else:
                if self._hex==False:
                    print(getList[i], ' ', gotList[i])
                elif self._hex == True:
                    print(getList[i],' ', hex(gotList[i]) )




    def putIOCPVs(self):
        putIOCOK = False
        putIOCPVs  = []

        if self._forceValue:
            putIOCOK =True
        else: 
            print(self._devices)
            print('Are you sure you want to caput to IOC PVs with extension :', self._ext, ' and put value: ', self._putValue, '? yes/no')
            caputOK = input()
            if caputOK == 'yes':
                putIOCOK=True


        if putIOCOK:
            putValuesArray = []
            for devName in self._devices:
                putIOCPVs.append(devName +':'+ self._ext)
                putValuesArray.append(self._putValue)
            for i in range(len( putIOCPVs)):
                print('Caputting IOC: ', putIOCPVs[i], ' ', self._putValue   )

    
            putList=epics.caput_many(putIOCPVs,putValuesArray)
            for i in range(len(putIOCPVs)):
                print(putIOCPVs[i], ' ', putList[i])



    def getBPMPVs(self):
        ####code in cannot have hex with string ######
        getList = []
        for devName in self._devices:
            temp = devName +':' + self._ext
            getList.append(temp)


        if self._numeric:
            gotList = epics.caget_many(getList)
        else:
            gotList = epics.caget_many(getList,as_string=True)


        for i in range(len(getList)):
            if gotList[i] is None:
                print('Channel connect timed out: ', getList[i],' not found.' )
            else:
                if self._hex==False :
                    print(getList[i], ' ', gotList[i])
                elif self._hex == True:
                    print(getList[i],' ', hex(int(gotList[i])) )



    def putBPMPVs(self):
        putBPMOK = False
        putBPMPVs  = []
        if self._forceValue:
            putBPMOK = True
        else:
            print(self._devices)
            print('Are you sure you want to caput to BPM PVs with extension :', self._ext, ' and put value: ', self._putValue, '? yes/no')
            caputOK = input()
            if caputOK == 'yes':
                putBPMOK = True

        if putBPMOK:
            for devName in self._devices:
                putBPMPVs.append(devName +':'+ self._ext)


            #for i in range(len( putBPMPVs)):
             #   print('Caputting BPMS: ', putBPMPVs[i], ' ', self._putValue   )


            tempPutArray =[]
            for i in range(len(putBPMPVs)):
                tempPutArray.append(self._putValue)
            putList=epics.caput_many(putBPMPVs,tempPutArray)
            

            for i in range(len(putBPMPVs)):
                if putList[i] == 1:
                    print(putBPMPVs[i],' was caput successfully')
                elif putList[i] == -1:
                    print(putBPMPVs[i],' has failed to be caput')



    def getTPRPVs(self):
        getList = []
        getListTPR = []
        getListFilt = {} 
        for devName in self._devices:
            temp = devName +':TPR'
            getList.append(temp)


        if self._numeric:
            gotList = epics.caget_many(getList)
        elif self._numeric == False: 
            gotList = epics.caget_many(getList,as_string=True)
        #print(gotList)


        for i in range(len(gotList)):
            if gotList[i] is None:
                print('Channel connect timed out: ', getList[i],' not found.' )
            else:
                #print(getList[i], ' ', gotList[i])
                #getListTPR.append(gotList[i]+':'+self._ext)
                getListFilt[gotList[i]+':'+self._ext] = 1
        getListTPR = list(getListFilt.keys())
        if self._numeric:
            gotListTPR = epics.caget_many(getListTPR)
        elif self._numeric == False:
            gotListTPR = epics.caget_many(getListTPR,as_string=True)


        for i in range(len(gotListTPR)):
            if gotListTPR[i] is None:
                print('Channel connect timed out: ', getListTPR[i],' not found.' )
            else:
                print(getListTPR[i] ,' ' ,gotListTPR[i])



    def putTPRPVs(self):
        putTPROK = False
        putListTPR = []
        getList = []
        putListFilt = {}
        for devName in self._devices:
            temp = devName +':TPR'
            getList.append(temp)


        if self._numeric:
            gotList = epics.caget_many(getList)
        else:
            gotList = epics.caget_many(getList,as_string=True)


        #for i in range(len(gotList)):
            #print(gotList[i])
        for i in range(len(gotList)):
            if gotList[i] is None:
                print('Channel connect timed out: ', getList[i],' not found.')
            else:
                #putListTPR.append(gotList[i]+':'+self._ext)
                putListFilt[gotList[i]+':'+self._ext] = 1
        putListTPR = list(putListFilt.keys())


        if self._forceValue:
            putTPROK = True
        else:
            print(putListTPR)
            print('Are you sure you would like to caput TPR PVs to value: ',self._putValue,'? yes/no')
            caputOK = input()
            if caputOK == 'yes':
                putTPROK = True

        if putTPROK: 
            print('OK to put')     
            tempPutValues = []

            for i in range(len(putListTPR)):
                tempPutValues.append(self._putValue)
                #print('Caputting TPR: ', putListTPR[i], ' ', self._putValue   )
            
            isPut = epics.caput_many(putListTPR,tempPutValues)

            for i in range(len(putListTPR)):
                if isPut[i] == 1:
                    print(putListTPR[i],' was caput successfully')
                elif isPut[i] == -1:
                    print(putListTPR[i],' has failed to be caput')    
          
        

    def updateExtension(self,updatedExtension):
        pass

    def updatePutValue(self,updatedPutValue):
        pass




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('-d' ,'--device', choices =['ioc','bpm', 'tpr'], default = 'ioc', help = "Specifies what type of device to get/put PVs for 'ioc,bpm,tpr'")
    parser.add_argument('-l','--location',nargs ='+', help= 'Optional flag that specifies the location eg. HTR, DMPH, BSY, NC, SC, etc. Multiple args can be used here to apply additional filters "-l SC HARD" ' )
    parser.add_argument('-R', '--rebootMode', action = 'store_true', help = 'On/Off flag that specifies whether or not you want to reboot IOCS')
    parser.add_argument('-e', '--extension',default = None, help = 'Extension appended to device that you want to know eg. STARTTOD ,STA_ALH, etc., The code will not without a -e unless there is a -R or -F command')
    parser.add_argument('-W', '--writePutValue', help = "Flag that caputs a value to a pv instead of cagets" )
    parser.add_argument('-F','--upgradeFirmware',help = "On/Off flag that tells the program to upgrade the firmware for all IOCS (optional use with -l LOCATION)", action = 'store_true')
    parser.add_argument('-dir', '--directory', default='/home/softegr/sonya/bpm/sc/fwupdate', help = 'Path to the directory where firmware results are written')
    parser.add_argument('-pr', '--programScript', default='/usr/local/lcls/package/cpsw/utils/ProgramFPGA/current/ProgramFPGA.bash',help = 'Path to the program script used for upgrading firmware')
    parser.add_argument('-mcs','--mcsFile',default='/usr/local/lcls/epics/iocTop/Bpm/firmware/current-stripline',help='Path to the mcs file')
    parser.add_argument('-0x', '--hex', action= 'store_true', help= 'On/Off flag the tells the script to convert integers value to hexi-decimal values ')
    parser.add_argument('-s', '--select', help = 'Optional flag for selecting one device e.g "-s SIOC:BC1B:BP01 -e STARTTOD -W 1/11/2023" will select this IOC and perform the operations given by the by the other flags.')
    parser.add_argument('-n','--numeric',action='store_true',help= 'Optional flag that specifies whether PV Value should be displayed as the index of enumerated string list rather that the contents of that list at the index. ')
    parser.add_argument('-f','--force',action='store_true',help= 'Optional flag that tells the program to override the protections put in place for invasive commands')
    args = parser.parse_args()
    print(args)

 
   
    ######still need completelist of common iocs
    iocs = ['SIOC:GUNB:BP01','SIOC:BC1B:BP01', 'SIOC:BC1B:BP02', 'SIOC:BC2B:BP01', 'SIOC:BC2B:BP02', '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', 'SIOC:BPN28:BP01', 'SIOC:COL0:BP01', 'SIOC:COL0:BP02', 'SIOC:COL0:BP03', 'SIOC:COL0:BP04', 
            'SIOC:COL0:BP05', 'SIOC:COL0:BP06', 'SIOC:COL0:BP07', 'SIOC:COL1:BP01', 'SIOC:COL1:BP02', 'SIOC:COL1:BP03', 'SIOC:COL1:BP04', 'SIOC:COL1:BP05', 
            'SIOC:DIAG0:BP01', 'SIOC:DIAG0:BP02', 'SIOC:DIAG0:BP03', 'SIOC:DIAG0:BP04', 'SIOC:DIAG0:BP05', '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:EMIT2:BP01', 'SIOC:EXT:BP01', 
            'SIOC:HTR:BP01', 'SIOC:HTR:BP02', 'SIOC:HTR:BP03', 'SIOC:HTR:BP04', 'SIOC:HTR:BP05', 'SIOC:L0B:BP01', 'SIOC:L1B:BP01', 'SIOC:L1B:BP02', 'SIOC:L1B:BP03', 
            'SIOC:L2B:BP01', 'SIOC:L2B:BP02', 'SIOC:L2B:BP03', 'SIOC:L2B:BP04', 'SIOC:L2B:BP05', 'SIOC:L2B:BP06', 'SIOC:L2B:BP07', '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:SLTD:BP01', 'SIOC:SLTH:BP01', 'SIOC:SLTS:BP01', 'SIOC:SLTS:BP02', 'SIOC:SPD:BP01', 'SIOC:SPD:BP02', 'SIOC:SPD:BP03', 'SIOC:SPD:BP04', 'SIOC:SPD:BP05',
            'SIOC:SPD:BP06', 'SIOC:SPH:BP01', 'SIOC:SPH:BP02', 'SIOC:SPH:BP03', 'SIOC:SPH:BP04', 'SIOC:SPH:BP05', 'SIOC:SPH:BP06', 'SIOC:SPH:BP07', 'SIOC:SPS:BP01', 
            'SIOC:SPS:BP02', 'SIOC:SPS:BP03', 'SIOC:SPS:BP04', 'SIOC:SPS:BP05', 
            'IOC:IN20:BP01', 'IOC:IN20:BP02', 'IOC:LI21:BP01', 'IOC:LI21:BP02', 'IOC:LI22:BP01', 'IOC:LI22:BP02', 'IOC:LI23:BP01', 'IOC:LI23:BP02', 'IOC:LI24:BP01', 
            'IOC:LI24:BP02', 'IOC:LI25:BP01', 'IOC:LI25:BP02', 'IOC:LI26:BP01', 'IOC:LI26:BP02', 'IOC:LI27:BP01', 'IOC:LI27:BP02', 'IOC:LI28:BP01', 'IOC:LI28:BP02', 
            'IOC:LI29:BP01', 'IOC:LI29:BP02', 'IOC:LI30:BP01', 'IOC:LI30:BP02', 'IOC:BSY0:BP01', 'EIOC:IN20:BP221', 'EIOC:IN20:BP235', 'EIOC:IN20:BP371', 'EIOC:IN20:BP425', 
            'EIOC:IN20:BP511', 'EIOC:IN20:BP525', 'EIOC:IN20:BP581', 'EIOC:IN20:BP631', 'EIOC:IN20:BP651', 'EIOC:IN20:BP731', 'EIOC:IN20:BP771', 'EIOC:IN20:BP781', 
            'EIOC:IN20:BP821', 'EIOC:IN20:BP925', 'EIOC:IN20:BP945', 'EIOC:IN20:BP981', 'EIOC:LI21:BP131', 'EIOC:LI21:BP161', 'EIOC:LI21:BP201', 'EIOC:LI21:BP233', 
            'EIOC:LI21:BP278', 'EIOC:LI21:BP301', 'EIOC:LI21:BP315', 'EIOC:LI21:BP401', 'EIOC:LI21:BP501', 'EIOC:LI21:BP601', 'EIOC:LI21:BP701', 'EIOC:LI21:BP801', 
            'EIOC:LI21:BP901', 'EIOC:LI22:BP201', 'EIOC:LI22:BP301', 'EIOC:LI22:BP401', 'EIOC:LI22:BP501', 'EIOC:LI22:BP601', 'EIOC:LI22:BP701', 'EIOC:LI22:BP801', 
            'EIOC:LI22:BP901', 'EIOC:LI23:BP201', 'EIOC:LI23:BP301', 'EIOC:LI23:BP401', 'EIOC:LI23:BP501', 'EIOC:LI23:BP601', 'EIOC:LI23:BP701', 'EIOC:LI23:BP801', 
            'EIOC:LI23:BP901', 'EIOC:LI24:BP201', 'EIOC:LI24:BP301', 'EIOC:LI24:BP401', 'EIOC:LI24:BP501', 'EIOC:LI24:BP601', 'EIOC:LI24:BP701', 'EIOC:LI24:BP801', 
            'EIOC:LI24:BP901', 'EIOC:LI25:BP201', 'EIOC:LI25:BP301', 'EIOC:LI25:BP401', 'EIOC:LI25:BP501', 'EIOC:LI25:BP601', 'EIOC:LI25:BP701', 'EIOC:LI25:BP801', 
            'EIOC:LI25:BP901', 'EIOC:LI26:BP201', 'EIOC:LI26:BP301', 'EIOC:LI26:BP401', 'EIOC:LI26:BP501', 'EIOC:LI26:BP601', 'EIOC:LI26:BP701', 'EIOC:LI26:BP801', 
            'EIOC:LI26:BP901', 'EIOC:LI27:BP201', 'EIOC:LI27:BP301', 'EIOC:LI27:BP401', 'EIOC:LI27:BP501', 'EIOC:LI27:BP601', 'EIOC:LI27:BP701', 'EIOC:LI27:BP801', 
            'EIOC:LI27:BP901', 'EIOC:LI29:BP201', 'EIOC:LI29:BP301', 'EIOC:LI29:BP401', 'EIOC:LI29:BP501', 'EIOC:LI29:BP601', 'EIOC:LI29:BP701', 'EIOC:LI29:BP801', 
            'EIOC:LI29:BP901', 'EIOC:LI30:BP201', 'EIOC:LI30:BP301', 'EIOC:LI30:BP401', 'EIOC:LI30:BP501', 'EIOC:LI30:BP601', 'EIOC:LI30:BP701', 'EIOC:LI30:BP801', 'EIOC:CLTH:BP140', 'EIOC:CLTH:BP170',
            'SIOC:CLTS:BP01', 'SIOC:CLTS:BP02', 'SIOC:CLTS:BP03', 'SIOC:CLTS:BP04', 'SIOC:CLTS:BP05', 'SIOC:CLTS:BP06', 'EIOC:LTUH:BP490', 'EIOC:LTUH:BP590', 'EIOC:LTUH:BP620', 
            'EIOC:LTUH:BP680', 'EIOC:LTUH:BP740', 'EIOC:LTUH:BP750', 'EIOC:LTUH:BP820', 'EIOC:LTUH:BP840', 'IOC:LTUH:BP02', 'IOC:LTUH:BP03', 'IOC:LTUH:BP04', 'IOC:UNDH:BP01','SIOC:BSYS:BP01', 'SIOC:LTUS:BP01', 'SIOC:LTUS:BP02', 'SIOC:LTUS:BP03', 'SIOC:LTUS:BP04', 'SIOC:LTUS:BP05', 'SIOC:LTUS:BP06', 'SIOC:LTUS:BP07', 'SIOC:LTUS:BP08', 'SIOC:LTUS:BP09', 'SIOC:LTUS:BP10', 'SIOC:LTUS:BP11', 'SIOC:LTUS:BP12', 'SIOC:LTUS:BP13', 'SIOC:LTUS:BP14', 'SIOC:LTUS:BP15', 'SIOC:LTUS:BP16', 'SIOC:LTUS:BP17', 'SIOC:UNDS:BP01', 'SIOC:UNDS:BP02', 'SIOC:UNDS:BP03', 'SIOC:UNDS:BP04', 'SIOC:UNDS:BP05', 'SIOC:UNDS:BP06', 'SIOC:UNDS:BP07', 'SIOC:UNDS:BP08', 'SIOC:UNDS:BP09', 'SIOC:UNDS:BP10', 'SIOC:UNDS:BP11', 'SIOC:UNDS:BP12', 'SIOC:UNDS:BP13', 'SIOC:UNDS:BP14', 'SIOC:UNDS:BP15', 'SIOC:DMPS:BP01', 'SIOC:DMPS:BP02', 'SIOC:BSYH:BP01', 'SIOC:BSYH:BP02', 'SIOC:BSYH:BP03', 'SIOC:LTUH:BP01', 'SIOC:LTUH:BP02', 'SIOC:LTUH:BP03', 'SIOC:LTUH:BP04', 'SIOC:LTUH:BP05', 'SIOC:LTUH:BP06', 'SIOC:LTUH:BP07', 'SIOC:LTUH:BP08', 'SIOC:LTUH:BP09', 'SIOC:LTUH:BP10', 'SIOC:LTUH:BP11', 'SIOC:LTUH:BP12', 'SIOC:LTUH:BP13', 'SIOC:LTUH:BP14', 'SIOC:LTUH:BP15', 'SIOC:UNDH:BP01', 'SIOC:UNDH:BP02', 'SIOC:UNDH:BP03', 'SIOC:UNDH:BP04', 'SIOC:UNDH:BP05', 'SIOC:UNDH:BP06', 'SIOC:UNDH:BP07', 'SIOC:UNDH:BP08', 'SIOC:UNDH:BP09', 'SIOC:UNDH:BP10', 'SIOC:UNDH:BP11', 'SIOC:UNDH:BP12', 'SIOC:UNDH:BP13', 'SIOC:UNDH:BP14', 'SIOC:UNDH:BP15', 'SIOC:UNDH:BP16', 'SIOC:UNDH:BP17', 'SIOC:UNDH:BP18', 'SIOC:UNDH:BP19', 'SIOC:UNDH:BP20', 'SIOC:DMPH:BP01', 'SIOC:DMPH:BP02']
            

    bpms =['BPMS:GUNB:314','BPMS:GUNB:925','BPMS:L0B:0183','BPMS:HTR:120','BPMS:HTR:320','BPMS:HTR:365','BPMS:HTR:460','BPMS:HTR:540',
            'BPMS:HTR:760','BPMS:HTR:830','BPMS:HTR:860','BPMS:HTR:960','BPMS:HTR:980','BPMS:COL0:135','BPMS:DIAG0:210','BPMS:COL0:240',
            'BPMS:COL0:260','BPMS:COL0:280','BPMS:COL0:320','BPMS:COL0:400','BPMS:COL0:480','BPMS:COL0:560','BPMS:COL0:640','BPMS:COL0:720',
            'BPMS:COL0:800','BPMS:COL0:880','BPMS:COL0:940','BPMS:DIAG0:190','BPMS:DIAG0:230','BPMS:DIAG0:270','BPMS:DIAG0:285',
            'BPMS:DIAG0:330','BPMS:DIAG0:370','BPMS:DIAG0:390','BPMS:DIAG0:470','BPMS:DIAG0:520','BPMS:L1B:0283','BPMS:L1B:0383','BPMS:L1B:H183',
            'BPMS:L1B:H283','BPMS:BC1B:125','BPMS:BC1B:440','BPMS:COL1:120','BPMS:COL1:260','BPMS:COL1:280','BPMS:COL1:320','BPMS:COL1:400',
            'BPMS:COL1:480','BPMS:COL1:560','BPMS:COL1:640','BPMS:COL1:720','BPMS:COL1:800','BPMS:COL1:880','BPMS:COL1:960','BPMS:L2B:0483',
            'BPMS:L2B:0583','BPMS:L2B:0683','BPMS:L2B:0783','BPMS:L2B:0883','BPMS:L2B:0983','BPMS:L2B:1083','BPMS:L2B:1183','BPMS:L2B:1283',
            'BPMS:L2B:1383','BPMS:L2B:1483','BPMS:L2B:1583','BPMS:BC2B:150','BPMS:BC2B:530','BPMS:EMIT2:150','BPMS:EMIT2:300','BPMS:EMIT2:800',
            'BPMS:EMIT2:900','BPMS:L3B:1683','BPMS:L3B:1783','BPMS:L3B:1883','BPMS:L3B:1983','BPMS:L3B:2083','BPMS:L3B:2183','BPMS:L3B:2283',
            'BPMS:L3B:2383','BPMS:L3B:2483','BPMS:L3B:2583','BPMS:L3B:2683','BPMS:L3B:2783','BPMS:L3B:2883','BPMS:L3B:2983','BPMS:L3B:3083',
            'BPMS:L3B:3183','BPMS:L3B:3283','BPMS:L3B:3383','BPMS:L3B:3483','BPMS:L3B:3583','BPMS:EXT:351','BPMS:EXT:748','BPMS:DOG:120',
            'BPMS:DOG:135','BPMS:DOG:150','BPMS:DOG:165','BPMS:DOG:180','BPMS:DOG:200','BPMS:DOG:215','BPMS:DOG:230','BPMS:DOG:250','BPMS:DOG:280',
            'BPMS:DOG:335','BPMS:DOG:355','BPMS:DOG:405','BPMS:DOG:575','BPMS:DOG:740','BPMS:DOG:910','BPMS:BPN13:400','BPMS:BPN14:400','BPMS:BPN15:400',
            'BPMS:BPN16:400','BPMS:BPN17:400','BPMS:BPN18:400','BPMS:BPN19:400','BPMS:BPN20:400','BPMS:BPN21:400','BPMS:BPN22:400',
            'BPMS:BPN23:400','BPMS:BPN24:400','BPMS:BPN25:400','BPMS:BPN26:400','BPMS:BPN27:400','BPMS:BPN28:200','BPMS:BPN28:400','BPMS:SPD:135',
            'BPMS:SPD:255','BPMS:SPD:340','BPMS:SPD:420','BPMS:SPD:525','BPMS:SPD:700','BPMS:SPD:955','BPMS:SPH:322','BPMS:SPH:345','BPMS:SPH:420',
            'BPMS:SPH:450','BPMS:SPH:520','BPMS:SPH:600','BPMS:SPH:675','BPMS:SPH:760','BPMS:SPH:840','BPMS:SPH:915','BPMS:SPH:940','BPMS:SPS:572','BPMS:SPS:580',
            'BPMS:SPS:640','BPMS:SPS:650','BPMS:SPS:710','BPMS:SPS:770','BPMS:SPS:780','BPMS:SPS:830','BPMS:SPS:840','BPMS:SLTS:150','BPMS:SLTH:200','BPMS:SLTH:220',
            'BPMS:SLTS:430','BPMS:SLTS:460','BPMS:SLTD:625','BPMS:SLTD:895',
            'BPMS:CLTH:215', 'BPMS:CLTS:420', 'BPMS:CLTS:450', 'BPMS:CLTS:470', 'BPMS:CLTS:500', 'BPMS:CLTS:510', 'BPMS:CLTS:540', 'BPMS:CLTS:570', 'BPMS:CLTS:590', 'BPMS:CLTS:620',
            'BPMS:IN20:221', 'BPMS:IN20:235', 'BPMS:IN20:371', 'BPMS:IN20:425', 'BPMS:IN20:511', 'BPMS:IN20:821', 'BPMS:IN20:525', 'BPMS:IN20:581', 
            'BPMS:IN20:631', 'BPMS:IN20:651', 'BPMS:IN20:731', 'BPMS:IN20:771', 'BPMS:IN20:781', 'BPMS:IN20:925', 'BPMS:IN20:945', 'BPMS:IN20:981', 
            'BPMS:LI21:131', 'BPMS:LI21:161', 'BPMS:LI21:201', 'BPMS:LI21:233', 'BPMS:LI21:278', 'BPMS:LI21:301', 'BPMS:LI21:315', 'BPMS:LI21:401', 
            'BPMS:LI21:501', 'BPMS:LI21:601', 'BPMS:LI21:701', 'BPMS:LI21:801', 'BPMS:LI21:901', 'BPMS:LI22:201', 'BPMS:LI22:301', 'BPMS:LI22:401', 
            'BPMS:LI22:501', 'BPMS:LI22:601', 'BPMS:LI22:701', 'BPMS:LI22:801', 'BPMS:LI22:901', 'BPMS:LI23:201', 'BPMS:LI23:301', 'BPMS:LI23:401', 
            'BPMS:LI23:501', 'BPMS:LI23:601', 'BPMS:LI23:701', 'BPMS:LI23:801', 'BPMS:LI23:901', 'BPMS:LI24:201', 'BPMS:LI24:301', 'BPMS:LI24:401', 
            'BPMS:LI24:501', 'BPMS:LI24:601', 'BPMS:LI24:701', 'BPMS:LI24:801', 'BPMS:LI24:901', 'BPMS:LI25:201', 'BPMS:LI25:301', 'BPMS:LI25:401', 
            'BPMS:LI25:501', 'BPMS:LI25:601', 'BPMS:LI25:701', 'BPMS:LI25:801', 'BPMS:LI25:901', 'BPMS:LI26:201', 'BPMS:LI26:301', 'BPMS:LI26:401', 
            'BPMS:LI26:501', 'BPMS:LI26:601', 'BPMS:LI26:701', 'BPMS:LI26:801', 'BPMS:LI26:901', 'BPMS:LI27:201', 'BPMS:LI27:301', 'BPMS:LI27:401', 
            'BPMS:LI27:501', 'BPMS:LI27:601', 'BPMS:LI27:701', 'BPMS:LI27:801', 'BPMS:LI27:901', 'BPMS:LI28:201', 'BPMS:LI28:301', 'BPMS:LI28:401', 
            'BPMS:LI28:501', 'BPMS:LI28:601', 'BPMS:LI28:701', 'BPMS:LI28:801', 'BPMS:LI28:901', 'BPMS:LI29:201', 'BPMS:LI29:301', 'BPMS:LI29:401', 
            'BPMS:LI29:501', 'BPMS:LI29:601', 'BPMS:LI29:701', 'BPMS:LI29:801', 'BPMS:LI29:901', 'BPMS:LI30:201','BPMS:LI30:301', 'BPMS:LI30:401',
            'BPMS:LI30:501', 'BPMS:LI30:601', 'BPMS:LI30:701', 'BPMS:LI30:801', 'BPMS:CLTH:140', 'BPMS:CLTH:170',
            'BPMS:BSYH:445', 'BPMS:BSYH:465', 'BPMS:BSYH:640', 'BPMS:BSYH:735', 'BPMS:BSYH:910', 'BPMS:BSYS:865', 'BPMS:DMPH:325', 'BPMS:DMPH:381', 
            'BPMS:DMPH:502', 'BPMS:DMPH:693', 'BPMS:DMPS:325', 'BPMS:DMPS:381', 'BPMS:DMPS:502', 'BPMS:DMPS:693', 'BPMS:LTUH:110', 'BPMS:LTUH:120', 
            'BPMS:LTUH:130', 'BPMS:LTUH:150', 'BPMS:LTUH:170', 'BPMS:LTUH:180', 'BPMS:LTUH:190', 'BPMS:LTUH:250', 'BPMS:LTUH:290', 'BPMS:LTUH:350', 
            'BPMS:LTUH:390', 'BPMS:LTUH:450', 'BPMS:LTUH:490', 'BPMS:LTUH:550', 'BPMS:LTUH:590', 'BPMS:LTUH:620', 'BPMS:LTUH:640', 'BPMS:LTUH:660', 
            'BPMS:LTUH:680', 'BPMS:LTUH:720', 'BPMS:LTUH:730', 'BPMS:LTUH:740', 'BPMS:LTUH:750', 'BPMS:LTUH:760', 'BPMS:LTUH:770', 'BPMS:LTUH:820', 
            'BPMS:LTUH:840', 'BPMS:LTUH:860', 'BPMS:LTUH:880', 'BPMS:LTUH:910', 'BPMS:LTUH:960', 'BPMS:LTUS:120', 'BPMS:LTUS:150', 'BPMS:LTUS:180', 
            'BPMS:LTUS:235', 'BPMS:LTUS:300', 'BPMS:LTUS:345', 'BPMS:LTUS:370', 'BPMS:LTUS:450', 'BPMS:LTUS:470', 'BPMS:LTUS:500', 'BPMS:LTUS:510', 
            'BPMS:LTUS:540', 'BPMS:LTUS:560', 'BPMS:LTUS:570', 'BPMS:LTUS:580', 'BPMS:LTUS:620', 'BPMS:LTUS:640', 'BPMS:LTUS:660', 'BPMS:LTUS:680', 
            'BPMS:LTUS:740', 'BPMS:LTUS:750', 'BPMS:LTUS:820', 'BPMS:LTUS:840', 'BPMS:LTUS:860', 'BPMS:LTUS:880', 'BPMS:UNDH:1305', 'BPMS:UNDH:1390', 
            'BPMS:UNDH:1490', 'BPMS:UNDH:1590', 'BPMS:UNDH:1690', 'BPMS:UNDH:1790', 'BPMS:UNDH:1890', 'BPMS:UNDH:1990', 'BPMS:UNDH:2090', 'BPMS:UNDH:2190', 
            'BPMS:UNDH:2290', 'BPMS:UNDH:2390', 'BPMS:UNDH:2490', 'BPMS:UNDH:2590', 'BPMS:UNDH:2690', 'BPMS:UNDH:2790', 'BPMS:UNDH:2890', 'BPMS:UNDH:2990', 
            'BPMS:UNDH:3090', 'BPMS:UNDH:3190', 'BPMS:UNDH:3290', 'BPMS:UNDH:3390', 'BPMS:UNDH:3490', 'BPMS:UNDH:3590', 'BPMS:UNDH:3690', 'BPMS:UNDH:3790', 
            'BPMS:UNDH:3890', 'BPMS:UNDH:3990', 'BPMS:UNDH:4090', 'BPMS:UNDH:4190', 'BPMS:UNDH:4290', 'BPMS:UNDH:4390', 'BPMS:UNDH:4490', 'BPMS:UNDH:4590', 
            'BPMS:UNDH:4690','BPMS:UNDH:4790',  'BPMS:UNDH:5190', 'BPMS:UNDS:1690', 'BPMS:UNDS:1990', 'BPMS:UNDS:2190', 'BPMS:UNDS:2490', 'BPMS:UNDS:2590', 'BPMS:UNDS:2690', 
            'BPMS:UNDS:2790', 'BPMS:UNDS:2890', 'BPMS:UNDS:2990', 'BPMS:UNDS:3090', 'BPMS:UNDS:3190', 'BPMS:UNDS:3290', 'BPMS:UNDS:3390', 'BPMS:UNDS:3490', 
            'BPMS:UNDS:3590', 'BPMS:UNDS:3690', 'BPMS:UNDS:3790', 'BPMS:UNDS:3890', 'BPMS:UNDS:3990', 'BPMS:UNDS:4090', 'BPMS:UNDS:4190', 'BPMS:UNDS:4290', 
            'BPMS:UNDS:4390', 'BPMS:UNDS:4490', 'BPMS:UNDS:4590', 'BPMS:UNDS:4690', 'BPMS:UNDS:4790', 'BPMS:UNDS:5190']
    
    
 #####start by parsing master lists to get a list bpms ore ioc that fit the loca provided   
    if args.device == 'ioc':
        if args.location:
            devList = DevicesWithLocation(loca= args.location , devType=args.device, devices = iocs)
        else:
            devList = DevicesWithLocation( devType=args.device, devices = iocs)
    elif args.device in ['bpm','tpr']:
        if args.location:
            devList = DevicesWithLocation(loca= args.location,devType =args.device, devices = bpms)
        else:
            devList = DevicesWithLocation(devType =args.device,  devices = bpms)

    #print(devList.ReturnDevices())
    devs = devList.ReturnDevices()
    if args.select:
        devs = [args.select]

    if args.rebootMode == True and args.device == 'ioc' and args.upgradeFirmware == False:
        print("Entering Reboot Mode")
        toolKit = RebootIOCs( devices= devs,forceValue=args.force)
    elif args.upgradeFirmware == True and args.rebootMode == False:
        print("Entering Firmware Update Mode")
        toolkit = UpdateFirmware(devices = devs,forceValue = args.force,directory=args.directory, script=args.programScript, mcsFile=args.mcsFile)
    elif args.rebootMode == False and args.upgradeFirmware == False:

        toolkit = PVValue(extension = args.extension,devices=devs,hexi=args.hex, numericTrue=args.numeric,forceValue =args.force, putValue=args.writePutValue)

        if args.device =='ioc' and args.extension is not None and args.writePutValue is None:
            toolkit.getIOCPVs()

        elif args.device =='ioc'and args.extension is not None and args.writePutValue:
            toolkit.putIOCPVs()

        elif args.device =='bpm' and args.extension is not None and args.writePutValue is None:
            toolkit.getBPMPVs()

        elif args.device =='bpm'and args.extension is not None and args.writePutValue:
            toolkit.putBPMPVs()

        elif args.device == 'tpr' and args.extension is not None and args.writePutValue is None:
            toolkit.getTPRPVs()

        elif args.device == 'tpr' and args.extension is not None and args.writePutValue:
            toolkit.putTPRPVs()
