"""
Autochanger moveAndClampFilterOnline sequence
=============================================
ccs-script autochangerMoveAndClampSequence.py -n 10 

"""
import sys
import time
from org.lsst.ccs.scripting import CCS
from java.time import Duration
from java.lang import Exception


class Autochanger(object):
    def __init__(self, subsystem_name, n_sequences):
        self.name = subsystem_name
        self.n_seq = n_sequences

        assert n_sequences > 0, "The number of sequences should be postive"

        self.onlineClamps = CCS.attachSubsystem(self.name + "/onlineClamps")
        self.trucks = CCS.attachSubsystem(self.name + "/autochangerTrucks")

    def wait_for_user(self, text):
        print "Next command: %s\n" % text
        print "Press any key to proceed..."
        return raw_input()

    def initialise_clamp_position(self):
        print "Initialisation.."

        if self.onlineClamps.sendSynchCommand("isLocked"):
            self.unlock()

        if self.onlineClamps.sendSynchCommand("isHomingDone"):
            self.open()
        else:
            self.open_and_homing()

    def open_and_homing(self):
        # self.wait_for_user("onlineClamps: openAndHoming")
        print "homing..."
        self.onlineClamps.sendSynchCommand("homing")
        
    def open(self):
        # self.wait_for_user("onlineClamps: open")
        print "openClamps..."
        self.onlineClamps.sendSynchCommand("openClamps")

    def close(self):
        # self.wait_for_user("onlineClamps: close")
        print "closeClamps..."
        self.onlineClamps.sendSynchCommand("closeClamps")

    def lock(self):
        # self.wait_for_user("onlineClamps: lock")
        print "lockClamps..."
        self.onlineClamps.sendSynchCommand("lockClamps")

    def unlock(self):
        # self.wait_for_user("onlineClamps: unlock")
        print "unlockClamps..."
        self.onlineClamps.sendSynchCommand("unlockClamps")
    
    def go_to_handoff(self):
        print "goToHandoff..."
        self.trucks.sendSynchCommand("goToHandoff")

    def move_and_clamp_filter_online(self):
        print "moveAndClampFilterOnline..."
        self.trucks.sendSynchCommand("moveAndClampFilterOnline")

    def test_sequence(self):
        self.go_to_handoff()
        self.move_and_clamp_filter_online()
        self.unlock()
        self.open()

    def timed_test_sequence(self):
        """Starting with trucks at ONLINE, clamps opened, homing done"""
        t0 = time.time()
        self.go_to_handoff()
        t1 = time.time()
        self.move_and_clamp_filter_online()
        t2 = time.time()
        self.unlock()
        t3 = time.time()
        self.open()
        t4 = time.time()

        sequence_duration = t4 - t0

        print "\n"
        print "Duration of actions:\n"
        print "\tgoToHandoff: %.3fs" % (t1 - t0)
        print "\tmoveAndClampFilter: %.3fs" % (t2 - t1)
        print "\tunlock: %.3fs" % (t3 - t2)
        print "\topen: %.3fs" % (t4 - t3)
        print "\t---"
        print "\ttotal sequence: %.3fs" % sequence_duration
        print "\n"

        return sequence_duration

    def run_sequence(self):
        print __doc__

        self.initialise_clamp_position()    

        total_duration = 0
        for i in range(self.n_seq):
            print "Sequence %d/%d" % (i+1, self.n_seq)
            duration = self.timed_clamp_test_sequence()
            total_duration += duration
        
        print "\n\n"
        print "FINAL RESULTS"
        print "-------------"
        print "%d sequences run" % self.n_seq
        print "average duration for sequence = %d ms" % (total_duration / self.n_seq * 1000)
        print "\n\n"


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-n", "--n_sequences", 
        type=int, default=1,
        help="Number of cycles to go through.")
    args = parser.parse_args()

    Autochanger('fcs/autochanger', args.n_sequences).run_sequence()
