#!/usr/bin/env python
#
# Makes an archive viewer config file for MAG PVs whose HSTBPLOT is set - up to 9 PVs per plot.
#
import sys
import os
import subprocess
import xmlrpclib
import csv

proxy = xmlrpclib.ServerProxy('http://lcls-archsrv/cgi-bin/ArchiveDataServer.cgi')
result = proxy.archiver.archives()
#
colors = [ -65536, -16776961, -16711936, -65281, -16777216, -10092391, -39424, -13395559, -6710887 ]
iColor = -1
maxColors = len(colors)
mag_secn_list = ['BACT', 'BCON', 'BDES', 'FBCK', 'IACT', 'IDES', 'BCTRL', 'STATE', 'STDZOK', 'INTLKSUMY', 'STDZDISABLE']

edl_name = os.getenv('EDM') + "/mgnt/mgnt_" + sys.argv[1].lower() + "_hist.edl"
edl_pv_raw = subprocess.check_output(['grep', 'MADNAME', edl_name]);

x = csv.reader(edl_pv_raw.splitlines(), delimiter=" ")
ll = list(x)
mag_list = []

for element in ll:
   mag_list.append(element[1][:-7])

#print mag_list

#
f=open(os.getenv('ARCHCONFIGFILES') + '/mag-specific.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')
#
chkpvs = []
pvs = []
#
for mag in mag_list:
   for secn in mag_secn_list:
      pv = mag + secn
      chkpv = pv + 'HSTBPLOT'
      chkpvs.append(chkpv)
      pvs.append(pv)
try:
   args = ['caget', '-t']
   args.extend(chkpvs)
   process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   (stdoutdata, stderrdata) = process.communicate()
   answers = [str(x) for x in stdoutdata.split('\n')]
   n = 0
   for ans in answers:
      YN = ans.strip()
      if YN == 'YES':
         iColor += 1
         if iColor < maxColors:
            pv = pvs[n]
            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')
      n += 1
except ValueError as e:
   print('FAILED!\n')
#

#
f.write('</AVConfiguration>\n')
f.close()
