#/usr/bin/python
import numpy as np
import time
import os
import ezca
import subprocess

def gpsnow():
    return int(subprocess.check_output(["tconvert", "now"]))

ezca = ezca.Ezca()

pause_time_s = 200  #3+ minutes per step
optimal_SQZ_angle_deg = 90
optimal_ASQZ_angle_deg = 50

# prefix of the output file names (logfile and html file)
fname = '1.8x_trans_IFO.log'
gps_start_str = "{}".format(gpsnow())
try:
    os.makedirs('logs/')
except:
    pass
fname = 'logs/' + gps_start_str + "_"+ fname

memo = """
IFO phase rotation
"""

with open(fname, 'w') as F:
    F.write("# squeezing angle rotation log file, gps start, gps stop, CLF polarity, CLF demod phase, LO_gain_IN1\n")
    #write a memo
    for line in memo.split('\n'):
        F.write("#" + line.strip() + "\n")

def log_append(logline):
    ### Save the logfile 	
    with open(fname, 'a') as F:
        linestr = ', '.join(["{}".format(l) for l in logline]) + '\n'
        F.write(linestr)
    return

#CLF sign 1 is inverted (SQZ MODE)
#run a measurement at optimal SQZ
for CLF_sign, CLF_angle, LO_gain  in [
        [1,   150,           0], 
        [1,   120,           0], 
        [1,   90,            0],
        [1,   60,            0],
        [1,   30,            0],
        [1,   0,             0],
        [0,   0,             3],
        [0,   20,            6],
        [0,   50,            6],
        [0,   80,            6],
        [0,   110,           0],
        [0,   140,           0],
        [1,   90,            0],
]:
    time.sleep(2)
    ezca['SQZ-CLF_SERVO_IN2POL'] = CLF_sign  #normal sign
    ezca['SQZ-LO_SERVO_IN1GAIN'] = LO_gain
    start_gps = gpsnow()
    ezca['SQZ-CLF_REFL_RF6_PHASE_PHASEDEG'] = CLF_angle
    time.sleep(pause_time_s)
    stop_gps = gpsnow()
    log_append([
        start_gps,
        stop_gps,
        ezca['SQZ-CLF_SERVO_IN2POL'],
        ezca['SQZ-CLF_REFL_RF6_PHASE_PHASEDEG'],
        ezca['SQZ-LO_SERVO_IN1GAIN']
    ])

