#!/usr/bin/env python

############################################################
# NAME: srf_makeAutoPlot.py                               
# Author: Janice Nelson                                    
# Created: 6/14/20                                         
#                                                          
# Description: Create config files for archiver or striptool
#              Called from edm or bash. Usage:
#              srf_makeAutoPlot.py var1 var2 vars
#              var1=av or st
#              var2 = plotname
#              vars = whatever info plotname needs to generate PVs
#                                                          
#              from py/edm shell command button
#
#   srf_makeAutoPlot.py var1 var2 vars ; lclsarch "srf_plotname.xml -plot"
# or
#   srf_makeAutoPlot.py var1 var2 vars ; StripTool $STRIP_CONFIGFILE_DIR/srf_plotname.stp
#
############################################################
#
import sys
import os

# for testing at LERF in case of differences
#
#ipcheck=os.getenv('EPICS_IOC_LOG_INET')
#if ipcheck[0:3]=='129' :
#  loca='lerf'
#else :
#  loca='slac'

# sanity checks
# enough variables passed
narg=len(sys.argv)
if narg<3 :
  print('Too few arguments. Usage: srf_makeAutoPlot.py av/st plotname vars')
  raise SystemExit

# archiver or striptool
configType=sys.argv[1].lower()
if configType not in ['av', 'st'] :
  print('Archiver or striptool config? av or st after script call')
  raise SystemExit

#all the plots the code knows how to make
# key is plotname, value is filename
plotNameDict = {
  "cavtemps": "srf_cavtemps",
  "cryopipe": "srf_cryopipe",
  "cplrtop": "srf_cplrtop",
  "cplrbot": "srf_cplrbot",
  "homus": "srf_homus",
  "homds": "srf_homds",
  "steptmps": "srf_steptmps",
  "cmcryos": "srf_cmcryos",
  "cmheves": "srf_cmheves",
  "cavhtrs": "srf_cavhtrs",
  "cmpiezov": "srf_cmpiezov",
  "cmvac": "srf_cmvac",
  "cmaact": "srf_cmaact",
  "cmpdes": "srf_cmpdes",
  "cmpact": "srf_cmpact",
  "cmmag": "srf_cmmag",
  "magtemps": "srf_magtemps"
}

plotName=sys.argv[2].lower()

if plotName not in plotNameDict :
  print('\n2nd arg needs to be a valid plot name\n')
  raise SystemExit
else :
  fileNamePrefix=plotNameDict[plotName]

# put rest of passed variables into arglist for plotName function
arglist=[]
if narg>3 :
  arglist=sys.argv[3:narg+1]
#  print('arglist {}'.format(arglist))

# global list of pvs for plot functions to write to
pvList=[]


# Plot Functions:
#
# cavtemps for one cavity
#
def cavtemps():
#  print('in cavtemps')
  if len(arglist)<2 :
    print('\ncavtemps needs two arguments: ACCL:LxB:nn (nn=1-35) and c (1-8)\n')
    raise SystemExit

  cm=arglist[0]
  cav=arglist[1]
  pvList.append(cm.upper()+cav+'0:STEPTEMP')
  pvList.append(cm.upper()+cav+'0:CPLRTEMP1')
  pvList.append(cm.upper()+cav+'0:CPLRTEMP2')
  pvList.append('CTE:CM'+cm[-2:]+':1'+cav+'20:DH:TEMP')
  pvList.append('CTE:CM'+cm[-2:]+':1'+cav+'18:UH:TEMP')

  if cav in ['1', '5'] :
    pvList.append('CTE:CM'+cm[-2:]+':1'+cav+'14:VT:TEMP')
    pvList.append('CTE:CM'+cm[-2:]+':1'+cav+'15:VB:TEMP')

#
# cryopipe temps in one CM
#
def cryopipe():
  if len(arglist)<1 :
    print('\ncryopipe needs one argument: ACCL:LxB:cm or cm (01-35,H1,H2)\n')
    raise SystemExit

  cm=arglist[0].upper()
  if cm[0]=='A' :
    cm=cm[-2:]

  pvPre='CTE:CM' + cm
  pvList.append(pvPre+':2501:A1:TEMP')
  pvList.append(pvPre+':2502:B1:TEMP')
  pvList.append(pvPre+':2503:B2:TEMP')
  pvList.append(pvPre+':2508:C1:TEMP')
  pvList.append(pvPre+':2509:D1:TEMP')
  pvList.append(pvPre+':2510:E1:TEMP')
  pvList.append(pvPre+':2511:F1:TEMP')
  pvList.append(pvPre+':2512:S1:TEMP')
  pvList.append(pvPre+':2514:CD:TEMP')
  pvList.append(pvPre+':2515:CD:TEMP')

#
# cplrtop all coupler top temps in one CM
#
def cplrtop():
  if len(arglist)<1 :
    print('\ncplrtop needs one argument: CM ACCL:LxB:yy, yy=01-35, H1, H2\n')
    raise SystemExit

  for nn in range(8) :
    pvList.append('{}{}0:CPLRTEMP1'.format(arglist[0],nn+1))

#
# cplrbot all coupler bottom temps in one CM
#
def cplrbot():
  if len(arglist)<1 :
    print('\ncplrbot needs one argument: CM ACCL:LxB:yy, yy=01-35, H1, H2\n')
    raise SystemExit

  for nn in range(8) :
    pvList.append('{}{}0:CPLRTEMP2'.format(arglist[0],nn+1))

#
# homus all HOM upstream temps in one CM
#
def homus():
  if len(arglist)<1 :
    print('\nhomus needs one argument: ACCL:LxB:cm or cm 01-35, H1, H2\n')
    raise SystemExit

  cm=arglist[0].upper()
  if cm[0]=='A' :
    cm=cm[-2:]
  for nn in range(8) :
    pvList.append('CTE:CM{}:1{}18:UH:TEMP'.format(cm,nn+1))

#
# homds all HOM upstream temps in one CM
#
def homds():
  if len(arglist)<1 :
    print('\nhomds needs one argument: ACCL:LxB:cm or cm 01-35, H1, H2\n')
    raise SystemExit

  cm=arglist[0].upper()
  if cm[0]=='A' :
    cm=cm[-2:]
  for nn in range(8) :
    pvList.append('CTE:CM{}:1{}20:DH:TEMP'.format(cm,nn+1))

#
# steptmps all stepper motor temps in one CM
#
def steptmps():
  if len(arglist)<1 :
    print('\nsteptmps needs one argument: CM ACCL:LxB:yy, yy=01-35, H1, H2\n')
    raise SystemExit

  for nn in range(8) :
    pvList.append('{}{}0:STEPTEMP'.format(arglist[0],nn+1))

  
#
# cmcryos various cryo things in one cm: LL, pres, valvs, cd htr
#
def cmcryos():
  if len(arglist)<1 :
    print('\ncmcryos needs one argument: ACCL:LxB:CM or CM = 01-35, H1, H2\n')
    raise SystemExit

  cm=arglist[0].upper()
  if cm[0]=='A' :
    cm=cm[-2:]
  pvList.append('CLL:CM'+cm+':2601:US:LVL')
  pvList.append('CLL:CM'+cm+':2301:DS:LVL')
  pvList.append('CPT:CM'+cm+':2602:US:PRESS')
  pvList.append('CPT:CM'+cm+':2302:DS:PRESS')
  pvList.append('CPV:CM'+cm+':3001:JT:POS_RBV')
  pvList.append('CPV:CM'+cm+':3002:CD:POS_RBV')
  pvList.append('CHTR:CM'+cm+':2261:CD:POWER')

#
# cmheves helium vessel temps from one cm
#
def cmheves():
  if len(arglist)<1 :
    print('\ncmheves needs one argument: ACCL:LxB:nn (nn=1-35) or cm (01-35,h1,h2)\n')
    raise SystemExit

  cm=arglist[0].upper()
  if cm[0]=='A' :
    cm=cm[-2:]
  for cav in ['1', '5'] :
    pvList.append('CTE:CM'+cm+':1'+cav+'14:VT:TEMP')
    pvList.append('CTE:CM'+cm+':1'+cav+'15:VB:TEMP')

#
# cavhtrs all cavity heaters in one CM
#
def cavhtrs():
  if len(arglist)<1 :
    print('\ncavhtrs needs one argument: CM ACCL:LxB:cm or cm 01-35, H1, H2\n')
    raise SystemExit

  cm=arglist[0].upper()
  if cm[0]=='A' :
    cm=cm[-2:]
  for nn in range(8) :
    pvList.append('CHTR:CM{}:1{}55:HV:POWER'.format(cm,nn+1))

#
# cmpiezov all piezo volts in one CM
#
def cmpiezov():
  if len(arglist)<1 :
    print('\ncmpiezov needs one argument: ACCL:LxB:cm cm=01-35, H1, H2\n')
    raise SystemExit

  for nn in range(8) :
    pvList.append('{}{}0:PZT:V'.format(arglist[0],nn+1))

#
# cmvac all vac in one CM
#   I don't know what these are
# these might be different lerf vs slac
#
def cmvac():
  if len(arglist)<2 :
    print('\ncmvac needs two arguments: LxB and unit\n')
    raise SystemExit

  area=arglist[0] #lxb
  unit=arglist[1] 
  pvList.append('VGCC:'+area+':0295:P')
  pvList.append('VGCC:'+area+':'+unit+':P')
  
#
# cmaact all AACTs in one CM
#
def cmaact():
  if len(arglist)<1 :
    print('\ncmaact needs one argument: ACCL:LxB:cm cm=01-35, H1, H2\n')
    raise SystemExit

  for nn in range(8) :
    pvList.append('{}{}0:AACT'.format(arglist[0],nn+1))

#
# cmpdes all PDESs in one CM
#
def cmpdes():
  if len(arglist)<1 :
    print('\ncmpdes needs one argument: ACCL:LxB:cm cm=01-35, H1, H2\n')
    raise SystemExit

  for nn in range(8) :
    pvList.append('{}{}0:PDES'.format(arglist[0],nn+1))

#
# cmpact all PACTs in one CM
#
def cmpact():
  if len(arglist)<1 :
    print('\ncmpact needs one argument: ACCL:LxB:cm cm=01-35, H1, H2\n')
    raise SystemExit

  for nn in range(8) :
    pvList.append('{}{}0:PACT'.format(arglist[0],nn+1))

#
# cmmag all magnet temps in one CM
#
def cmmag():
  if len(arglist)<1 :
    print('\ncmmag needs one or two arguments: ACCL:LxB:cm OR')
    print('area (LxB) and CM 01-35, H1, H2\n')
    raise SystemExit

  area=arglist[0].upper()
  if area[0]=='A' :
    cm=area[-2:]
    area=area[5:8]
  else :
    try :
      cm=arglist[1]
    except :
      print('\ncmmag needs one or two arguments: ACCL:LxB:cm OR')
      print('area (LxB) and CM 01-35, H1, H2\n')
      raise SystemExit

  for mType in ['QUAD', 'XCOR', 'YCOR'] :
    pvList.append(mType+':'+area+':'+cm+'85:BACT')
#
# decode MG ioc number. 
# L0B CM01 MG01-03
# L1B CM02 MG01-03
# L1B CM03 MG04-06 (cm-1)*3
# L2B CM04 MG01-03
# L2B CM15 MG34-36 (cm-3)*3
# L3B CM16 MG01-03 (cm-15)*3
# L3B CM35 MG58-60
  cmNum=int(cm)
  areaNum=int(area[1])
  if areaNum==0 :
    mgmax=3
  elif areaNum==1 :
    mgmax=(cmNum-1)*3
  elif areaNum==2 :
    mgmax=(cmNum-3)*3
  else : # boy I hope areaNum==3
    mgmax=(cmNum-15)*3

  mgNums=[]
  for nn in range(mgmax-2,mgmax+1) :
    numstr=str(nn)
    mgNums.append(numstr.zfill(2))
    
  for mgNum in mgNums :
    pvList.append('PSC:'+area+':MG'+mgNum+':PSVOUT')

  pvList.append('CHTR:CM'+cm+':2140:MP:POWER')

#
# magtemps all magnet temps in one CM
#
def magtemps():
  if len(arglist)<1 :
    print('\nmagtemps needs one argument: CM ACCL:LxB:cm or cm 01-35, H1, H2\n')
    raise SystemExit

  cm=arglist[0].upper()
  if cm[0]=='A' :
    cm=cm[-2:]
  for nn in range(4) :
    pvList.append('CTE:CM{}:240{}:MP:TEMP'.format(cm,nn+1))
  for nn in range(4) :
    pvList.append('CTE:CM{}:240{}:CL:TEMP'.format(cm,nn+5))

#
# End function definitions
#

# This calls the function whose name is stored in plotName
globals()[plotName]()

#print(pvList)

if configType == 'st':
  #Create config file
  f=open(os.getenv('STRIP_CONFIGFILE_DIR') + '/'+fileNamePrefix+'.stp', 'w')
#  f=open(fileNamePrefix+'.stp', 'w')

  # Write header
  f.write('StripConfig                     1.2\n')
  f.write('Strip.Time.Timespan             300\n')
  f.write('Strip.Time.NumSamples           65536\n')
  f.write('Strip.Time.SampleInterval       0.500000\n')
  f.write('Strip.Time.RefreshInterval      0.500000\n')
  f.write('Strip.Color.Grid                49071     49071     49071\n')
  f.write('Strip.Color.Background          65535     65535     65535\n')
  f.write('Strip.Color.Foreground          0     0     0\n')
  f.write('Strip.Option.GridXon            1\n')
  f.write('Strip.Option.GridYon            1\n')
  f.write('Strip.Option.AxisYcolorStat     1\n')
  f.write('Strip.Option.GraphLineWidth     2\n')

  # Write PV names, 10 max
  for nn in range(len(pvList[0:10])) :
    str = 'Strip.Curve.{}.Name              ' + pvList[nn] + '\n'
    f.write(str.format(nn))

  # Close file

  f.close()
