#!/usr/bin/env python

# Mike Zelazny
# Generates a report of Out-of-Tolerance Klystron Perveance

import os
import datetime
import subprocess
import subprocessca
import string
import KlystronList

f=open(os.getenv('LCLS_DATA') + '/physics/amrf/klydata/perv/' + str(datetime.date.today()), 'w')

f.write('Out of Tolerence Klystron Perveance (Less than 1.75)\n\n')
f.write('   Report Generated ' + str(datetime.date.today()) + ' ' + datetime.datetime.now().strftime("%H:%M:%S") + '\n\n')

f.write('     Station       Name    Perveance   Percent change (30 days)\n')
f.write('   ------------   ------   ---------   ------------------------\n')

KLYS = KlystronList.KlystronList()
for klystron in KLYS:

    try:
         process = subprocess.Popen([ 'aidaget',  klystron + '//PERV' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
         perv = string.rstrip(process.communicate()[0])
         ok = 0
         if float(perv) == 0:
              perv = '  ' + string.rstrip(subprocessca.get(klystron + ':PERV'))
         if float(perv) < 1.75:
              if float(perv) > 0.1:
                  process = subprocess.Popen([ 'aidaget',  klystron + '//NAME' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                  name = string.rstrip(process.communicate()[0])
                  process = subprocess.Popen([ 'aidaGetHist', klystron + ':PERV', '30 days ago' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                  h = process.communicate()
                  iToken = 0
                  for token in string.split(h[0]):
                      iToken += 1
                      if (1 == iToken):
                          date30 = token
                      if (2 == iToken):
                          time30 = token
                      if (3 == iToken):
                          p30 = token
                  if '' == h[0]:
                      f.write('   ' + string.replace(string.ljust(klystron,13,' '),':',' ') + string.ljust(name,9,' ') + perv + '\n\n')
                  else:
                      pctdiff = 100*(abs(float(perv)-float(p30))/float(perv))
                      f.write('   ' + string.replace(string.ljust(klystron,13,' '),':',' ') + string.ljust(name,9,' ') + string.ljust(perv,14,' ') + str(round(pctdiff,2)) + '% was ' + p30 + ' on ' + date30 + ' ' + time30 + '\n\n') 
    except ValueError as e:
         pass # Do nothing

f.close()
