#!/usr/bin/env python
#
# Makes an archive viewer config file for KLYS PVs whose HSTPLOT is set - up to 9 PVs per plot.
#
import sys
import os
import subprocess
import xmlrpclib
#
colors = [ -65536, -16776961, -16711936, -65281, -16777216, -10092391, -39424, -13395559, -6710887 ]
iColor = -1
maxColors = len(colors)
#
f=open(os.getenv('ARCHCONFIGFILES') + '/klys-dmp1.xml', 'w')
f.write('<?xml version="1.0" encoding="UTF-16"?>\n')
f.write('<AVConfiguration>\n')
f.write('    <connection_parameter>pbraw://lcls-archapp.slac.stanford.edu/retrieval</connection_parameter>\n')
f.write('    <time_axis name="Main Time Axis">\n')
f.write('        <start>-1d</start>\n')
f.write('        <end>now</end>\n')
f.write('        <location>bottom</location>\n')
f.write('    </time_axis>\n')
f.write('    <range_axis name="Main Range Axis">\n')
f.write('        <min/>\n')
f.write('        <max/>\n')
f.write('        <type>normal</type>\n')
f.write('        <location>left</location>\n')
f.write('    </range_axis>\n')
f.write('    <legend_configuration show_ave_name="true" show_directory_name="false" show_range="true" show_units="true"/>\n')
f.write('    <plot_title/>\n')
#
for num in range(1,200):
   pv = 'KLYS:DMP1:1:' + sys.argv[1] + 'HSTPLOT' + str(num)
   args = ['caget', '-t', pv]
   process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   (stdoutdata, stderrdata) = process.communicate()
   OK = stderrdata.strip()
   if OK in ('','epicsThreadOnceOsd epicsMutexLock failed.'):
      YN = stdoutdata.strip()
      if YN == 'YES':
         iColor += 1
         if iColor < maxColors:
            pv = 'KLYS:DMP1:1:' + sys.argv[1] + 'HSTPLOT' + str(num) + ':DESC.DESC'
            args = ['caget', '-t', pv]
            process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            (stdoutdata, stderrdata) = process.communicate()
            pv = stdoutdata.strip()
            f.write('    <pv directory_name="Default" name="' + pv + '">\n')
            f.write('        <time_axis_name>Main Time Axis</time_axis_name>\n')
            f.write('        <range_axis_name>Main Range Axis</range_axis_name>\n')
            f.write('        <color>' + str(colors[iColor]) + '</color>\n')
            f.write('        <draw_type>steps</draw_type>\n')
            f.write('        <draw_width>1.0</draw_width>\n')
            f.write('        <visibility>true</visibility>\n')
            f.write('    </pv>\n')
   else:
      break
#
f.write('</AVConfiguration>\n')
f.close()
#
# [EOF]
