#! /usr/bin/env python

__author__ = "chevtsov"
__date__ = "$Jul 15, 2010 3:35:05 PM$"

import sys

from subprocess import call
from fbckcontrol import common
from fbckcontrol import edef
import fbckconfig
import argparse
import subprocess
import time

def process_args(argv):
     parser=argparse.ArgumentParser(description='This script determines a refrence orbit and allows it to be saved')
     parser.add_argument('-loop',required=True, type = str, help = 'The loop prefix e.g. FB02:TR05')
     parser.add_argument('-beamcode',required=False,choices = [1,2], type = int, help='HXR = 1, SXR = 2: Default to HXR')
     parser.add_argument('-num',required=False, type = int, help='Number of measurments')
     parser.add_argument('-ouo',required=False,choices = ['Yes','No'], type = str, help='Orbit Update Only, Saves orbit without updating set points or actuator refrences')
     parser.add_argument('-ro',required=False,choices = ['Yes','No'], type = str, help='Reset Orbit, Removes the current saved refrence orbit')
     parser=parser.parse_args()
     
     return parser
     
def restart_loop(feedback_id):
     if common.caget('FBCK:'+feedback_id + ':STATE') == 'ON':
          common.caput('FBCK:'+feedback_id + ':STATE', 'OFF')
          common.caput('FBCK:'+feedback_id + ':STATE', 'ON')
          return
     

def main(argv):
    options = process_args(argv)
    #gets the feedback loop we are reading
    feedback_id = options.loop
    
    #Inteprete the parsed values
    #if an line code is sent Set the beam_char which will skip the dialogue and set the beam code
    if options.beamcode == 1:
        beam_char = 'H'
    elif options.beamcode == 2:
        beam_char = 'S'
    else:
        beam_char = ''
    #if the number of measurments has been spesified set it
    if options.num:
         avgcnt = options.num
    else:
         avgcnt = 0
    #if only the orbit should be saved
    if options.ouo == 'Yes':
         orbit_only_char = 'Y'
    elif options.ouo == 'No':
         orbit_only_char = 'n'
    else:
         orbit_only_char = ''
         
    #If only the orbit is being reset there is no need for any more computation
    #If the program should only reset the orbit
    if options.ro == 'Yes':
         resetOrbitOnly = True
    else:
         resetOrbitOnly = False
         
    if resetOrbitOnly:
         print 'Clearing set points...'
         if common.clear_setpoints(feedback_id) == False:
              print 'Failed to clear set points'
              return
         print 'Set points cleared.'
         return

    print 'Acquiring actuator data...'

    act_pvs_vals = common.act_pvs_vals(feedback_id)
    if act_pvs_vals == None or len(act_pvs_vals) == 0:
        print "No actuators configured."
        time.sleep(1.5)
        return
    print 'Actuator data collected.\n'

    while beam_char != 'H' and beam_char != 'S':
         beam_char = raw_input('Are you calculating orbit for the HXR or SXR (H/S): ')[0]
         
    if beam_char == 'H':
         beam_code = 1
    elif beam_char == 'S':
         beam_code = 2
    
    print 'Acquiring beam parameters...'

    hxr_rate_pv = 'EVNT:SYS0:1:NC_HARD_INJRATE'
    sxr_rate_pv = 'EVNT:SYS0:1:NC_SOFT_INJRATE'
    beamrate = 0
    if beam_code == 1:
         beamrate = common.caget(hxr_rate_pv)
    else:
         beamrate = common.caget(sxr_rate_pv)

    print 'The current beam rate is:', beamrate , 'Hz'
    
    if beamrate == 0:
         print 'Selected line is off'
         return

    if avgcnt > 0:
         print 'The number of measurments to be collected is:', avgcnt 

    else:  
         while True:
              try:
                   avgcnt = int(raw_input('Enter the number of measurments you would like (standard is 10): '))
                   break
              except ValueError:
                   print("Invalid Input")
              continue

    meascnt = 1
    timeout = 10

    if beamrate > 0:
        timeout = avgcnt / beamrate + 10
        
    print 'Beam parameters collected.\n'
    
    print 'Acquiring orbit data...'

    edef_number = edef.acquire('fbck_collect_orbit', avgcnt, meascnt, timeout, beam_code)
    if edef_number == -1:
        print 'No EDEF number avialable unable to collect data'
        return
    orbit_pvs_vals = common.orbit_pvs_vals(feedback_id, edef_number)
    edef.release(edef_number)
    
    #This code block reads current refrence positons and orbit here

    curr_act_pos = common.caget('FBCK:'+feedback_id + ':ACTREF')

    curr_ref_orbit = common.caget('FBCK:'+feedback_id + ':REFORBIT')

    print 'Orbit data collected.\n'

    print 'Actuator and Orbit data printouts\n'
    orbit_data_only = []
    act_data_only = []
    print 'Actuator Data'
    print '{:} \t{:>24}  \t{:>9} '.format('Devices','Collected Values','Current Act Ref')
    for i in xrange(0,len(act_pvs_vals),2):
         print act_pvs_vals[i],'\t', 
         print '{:18.15f}'.format(act_pvs_vals[i+1], ' '),
         print '\t',
         print '{:18.15f}'.format(curr_act_pos[i/2], ' ')
         act_data_only.append(act_pvs_vals[i+1])   
    print '\n'
    
    print 'Orbit Data'
    print '{:} \t{:>24}  \t{:>9} '.format('Devices','Collected Values','Current References Orbit')
    for i in xrange(0,len(orbit_pvs_vals),2):
         print orbit_pvs_vals[i],'\t', 
         print '{:18.15f}'.format(orbit_pvs_vals[i+1], ' '),
         print '\t', 
         print '{:18.15f}'.format(curr_ref_orbit[i/2], ' ')
         orbit_data_only.append(orbit_pvs_vals[i+1])
    print '\n'

    save_char = ''
    while save_char != 'Y' and save_char != 'n':
         save_char = raw_input('Would you like save refrence orbit (Y/n): ')[0]
         
    if save_char == 'n':
         print 'You can now close this window'
         return
         

    while orbit_only_char != 'Y' and orbit_only_char != 'n':
         orbit_only_char = raw_input('Would you like to only save the orbit without changing the actuator refrences and set points (Y/n): ')[0]
   
    
    if orbit_only_char == 'Y':
        print 'Saving reference orbit...'
        if common.save_ref_orbit(feedback_id, orbit_data_only) == False:
            return
        print 'Reference orbit saved.'
        restart_loop(feedback_id)
        print 'You can now close this window'
        return

    if save_char == 'Y':
        print 'Updating actuator references...'
        if common.update_act_refs(feedback_id, act_data_only) == False:
            return
        print 'Actuator references updated.'
        print 'Clearing set points...'
        if common.clear_setpoints(feedback_id) == False:
            return
        print 'Set points cleared.'
        print 'Saving reference orbit...'
        if common.save_ref_orbit(feedback_id, orbit_data_only) == False:
            return
        print 'Reference orbit saved.'
        restart_loop(feedback_id)
        print 'You can now close this window'
        return

if __name__ == "__main__":
    main(sys.argv[1:])
#    time.sleep(1.5)
