# Tool to align the solenoid on the gun.
# S. Bettoni, A. Gobbo, D. Voulot
# 06/06/2016
#Code ok with the GUI

# Procedure:
    # switch off all the magnets between the gun solenoid and the screen or BPM used for the measurement
    # change the current of the gun soleoid
    # look at the centroid position (BPM or screen) downstream of the gun.

import datetime

mode = "camtool"  # "camtool", "bpm" or "direct"
camera_name = "simulation"


def laser_on():
    print "Laser On"
    
def laser_off():
    print "Laser Off"

def is_laser_on():
    return False
        
def switch_off_magnets(magnets = None):
    print "switch_off_magnets"


    
gun_phase = cv


if get_exec_pars().source == CommandSource.ui:
    phi1= 95.0
    phi2 = 100.0
    dphi = 0.5
    settling_time = 0.5
    plot_image = False    
    number_images = 5
    use_background = False
    multiple_background = False
    number_backgrounds = 5
    do_elog = False    
    centroid_excursion_plot = True
else:    
    centroid_excursion_plot = False
    
#check_camtool()
    
laser_was_on = is_laser_on()
original_phase = gun_phase.read()
multiple_background = multiple_background and use_background   
print "Parameters: ", phi1, phi2, dphi, settling_time, plot_image, number_images, use_background, multiple_background, number_backgrounds 

plot_name = datetime.datetime.fromtimestamp(time.time()).strftime('%H%M%S')

if mode == "camtool":
    if (camtool.getCurrentCamera() != camera_name) or (camtool.getPipelinePars()["background_subtration"] != use_background):
        camtool.start(camera_name, None, use_background, None, None, None)        
        setBackgroundSubtraction
    if use_background:    
        laser_off()
        if not multiple_background:
            camtool.grabBackground(None, number_backgrounds)
else:
    if mode == "bpm":
        add_device(BpmStats("image_stats", camera_name), True)
    else :
        add_device(ImageStats(PsiCamera("image_stats", camera_name)), True)
    multiple_background = False
    use_background = False
    image_stats.setNumberOfImages(max(number_images,1))

#switch_off_magnets()

# add here gun phase setting see wiki page

def before_sample():    
    if multiple_background:
        camtool.grabBackground(None, number_backgrounds)
        laser_on()            
    if mode != "camtool":
        image_stats.update()
      
    
def after_sample():
    if multiple_background:
        laser_off()    
     
r = None
if not multiple_background:
    laser_on()

try:    
    if mode != "camtool":
        sensors = [image_stats.com_x_mean, image_stats.com_y_mean, image_stats.com_x_stdev, image_stats.com_y_stdev] 
    else:
        sensors = [CamtoolValue("gr_x_fit_mean"), CamtoolValue("gr_y_fit_mean"),  CamtoolValue("gr_x_fit_standard_deviation"),  CamtoolValue("gr_y_fit_standard_deviation")]
    if plot_image and (mode == "camtool"):
            sensors.append(CamtoolImage())
    r = lscan(gun_phase, sensors , phi1, phi2, dphi, settling_time, before_read = before_sample, after_read = after_sample)
    #tscan(sensors, 10, 1.0, before_read = before_sample, after_read = after_sample)
finally:
    pass 

gun_phase.write(original_phase)
if laser_was_on:
    laser_on()
else:
    laser_off()

# take the result of the scan and generate convex hull plot
if centroid_excursion_plot:
    (hx,hy)=add_convex_hull_plot ("Centroid excursion", r.getReadable(0),r.getReadable(1), plot_name)
else:   
    (hx,hy)= convex_hull(x=r.getReadable(0), y=r.getReadable(1))
    hx.append(hx[0]); hy.append(hy[0])        

"""
# save the entry in the logbook
gsa_log_msg = "Data file: " + get_exec_pars().path
gsa_log_msg = gsa_log_msg + "\nImages: " + str(number_images) + " Background: enabled=" + str(use_background) + " multiple="  + str(multiple_background) + " number="  + str(number_backgrounds) 
gsa_log_msg = gsa_log_msg + "\nPhase range: " + str(phi1) + " to " + str(phi2)
gsa_log_msg = gsa_log_msg + "\nLaser position on cathod: " + str(caget("SLG-LCAM-C103:FIT-XPOS")) + "/" + str(caget("SLG-LCAM-C103:FIT-YPOS"))
gsa_log_msg = gsa_log_msg + "\n\n" + r.print()
if do_elog:
    elog("Laser alignment with phase scan", gsa_log_msg , get_plot_snapshots())
"""
set_return([r, hx, hy])




