"""
FCS set filter sequence
=======================

"""
from org.lsst.ccs.scripting import CCS
from org.lsst.ccs.command import *
from java.time import Duration
from java.lang import Exception
from time import sleep, time
from random import shuffle

CCS.setThrowExceptions(True)

socket2filter = {
    1: 17,
    2: 3,
    3: 60,
    4: 15,
    5: 34,
}

class SetFilterSequence(object):
    name = "fcs"

    def __init__(self, n_sequences, handoff_only, random):
        self.n_seq = n_sequences
        self.handoff_only = handoff_only
        self.random = random

        self.subsystem = CCS.attachSubsystem(self.name, 1)
        print("Connected to fcs")
        print(self.subsystem.sendSynchCommand("getCCSVersions"))

        self.config = self.subsystem.sendAsynchCommand("getConfigurationInfo").get()

        self.timeout = Duration.ofMinutes(3)

    def setFilter(self, socketId):
        filterId = socket2filter[socketId]
        print("switching to filter %d on socket %d.." % (filterId, socketId))

        t0 = time()

        if self.handoff_only:
            self.subsystem.sendSynchCommand(self.timeout, "setFilterWithSafety", filterId)
        else:
            self.subsystem.sendSynchCommand(self.timeout, "setFilter", filterId)

        elapsed_time = time() - t0

        print("\t..took %dmin%ds" % (elapsed_time // 60, elapsed_time % 60))

    def setFilterSequence(self):
        socket_order = range(1, 6)
        if self.random:
            shuffle(socket_order)
        
        t0 = time()
        
        for socket in socket_order:
            self.setFilter(socket)

        elapsed_time = time() - t0

        print("=> sequence took %dmin%ds\n" % (elapsed_time // 60, elapsed_time % 60))

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

        for i in range(self.n_seq):
            print("Starting sequence %d/%d" % (i + 1, self.n_seq))
            self.setFilterSequence()

        print("Done")
    

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-n", "--n_sequences", 
        type=int, default=1, 
        help="Number of full sequences executed (default 1)")
    parser.add_argument(
        "--handoff", 
        action='store_true', 
        help="Filter never go past HANDOFF position")
    parser.add_argument(
        "-r", "--random", 
        action='store_true', 
        help="Randomises the sockets order between exchanges")

    args = parser.parse_args()

    SetFilterSequence(args.n_sequences, args.handoff, args.random).run()
