"""
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,
}

socket_order = [
    1, 2, 3, 4, 5, 
    2, 4, 1, 3, 5, 
    3, 1, 4, 2, 5, 
    4, 3, 2, 1, 5
]

class SetFilterSequence(object):
    name = "fcs"

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

        self.subsystem = CCS.attachSubsystem(self.name)
        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()

        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):
        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(
        "-r", "--random", 
        action='store_true', 
        help="Randomises the sockets order between exchanges")

    args = parser.parse_args()

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