"""
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.system = CCS.attachSubsystem(main_subsystem)
        self.carousel = CCS.attachSubsystem("%s/carousel" % main_subsystem)
        self.socket1 = CCS.attachSubsystem("%s/carousel/socket1" % main_subsystem)

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

        print("")
        print("Initialisation")
        print("--------------")

        if not self.socket1.sendSynchCommand("isAtStandby"):
            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, last=1):
        """Move to each socket and come back"""
        print("")
        print("Rotation sequence %d/%d" % (idx, last))
        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, last=self.n_seq)
    

if __name__ == "__main__":
    import argparse

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

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