"""
Carousel rotation sequence
==========================
Move carousel from socket 1 to each socket and back
"""
from org.lsst.ccs.scripting import CCS
from random import choice
from time import sleep, time


class CarouselSequence(object):

    def __init__(self, main_subsystem, n_sequences):
        self.n_seq = n_sequences

        self.carousel = CCS.attachSubsystem("%s/carousel" % main_subsystem)
        system = CCS.attachSubsystem(main_subsystem)
        self.config = system.sendAsynchCommand("getConfigurationInfo").get()

    def initialiseCarousel(self):
        """Perform homing and go to socket1"""

        print("")
        print("Initialisation")
        print("--------------")
        print("Homing..")
        self.carousel.sendSynchCommand("homing")

        current_position = int(self.carousel.sendSynchCommand("getPosition"))
        socket1_absolute_position = int(self.config.getCurrentValueForParameter("socket1/standbyPosition"))
        dpos = 500  # microns

        carousel_at_socket1 = abs(current_position - socket1_absolute_position) < dpos
        if not carousel_at_socket1:
            print("Carousel moving to socket 1")
            self.rotateToSocket(1)

    def rotateToSocket(self, socket_id):
        """Rotate the carousel to a given socket number"""
        self.carousel.sendSynchCommand("rotateSocketToStandby", "socket%d" % socket_id)
        sleep(2)

    def classicSequence(self, idx=1, nidx=1):
        """Move to each socket and come back"""
        print("")
        print("Rotation sequence %d/%d" % (idx, nidx))
        print("---------------------")
        t0 = time()
        for socket_id in [2, 3, 4, 5]:
            print("- rotating from socket 1 to socket %d" % socket_id)
            self.rotateToSocket(socket_id)
            print("- rotating from socket %d to socket 1" % socket_id)
            self.rotateToSocket(1)
        elapsed_sec = time() - t0
        minutes, sec = int(elapsed_sec // 60), int(elapsed_sec % 60)
        print("")
        print("time elapsed: %d'%d" % (minutes, sec))

    def run(self):
        """Execute the sequence"""
        print(__doc__)

        self.initialiseCarousel()
    
        for i in range(self.n_seq):
            self.classicSequence(idx=i+1, nidx=self.n_seq)
    

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser("toto")
    parser.add_argument(
        "-s", "--subsystem", 
        type=str, choices=["fcs", "carousel-standalone", "carousel-standalone_PROTO"], default="fcs", 
        help="Name of the running subsystem: 'fcs' or 'carousel-standalone' or 'carousel-standalone_PROTO'")
    parser.add_argument(
        "-n", "--n_sequences", 
        type=int, default=1, 
        help="Number of full sequences executed (default 1)")
    args = parser.parse_args()

    CarouselSequence(args.subsystem, args.n_sequences).run()
