nnnimport sys
import os
import argparse
import cothread.catools as ca
import time
import math

RUNNING = 2
TIMEOUT = 300  # seconds, may need update


class BatchControl(object):
    def __init__(self, racks):

        pvs_sel = []
        pvs_start = []
        pvs_stat = []
        for rack in racks:
            pvsel = ("%s:%s" % (rack, "TESTSEL"))
            pvstart = ("%s:%s" % (rack, "TESTSTRT"))
            pvstat = ("%s:%s" % (rack, "TESTSTAT"))

            try:
                sel = ca.caget(pvsel)
            except Exception:
                print("Error reading %s PVs. Skipping this rack" % rack)
                continue

            if sel:
                try:
                    ca.caget(pvstart)
                    ca.caget(pvstat)
                except Exception:
                    print("Error reading %s PVs. Skipping this rack" % rack)
                    continue

                pvs_sel.append(pvsel)
                pvs_start.append(pvstart)
                pvs_stat.append(pvstat)
                print("Including rack %s in list" % rack)

        l = len(pvs_sel)
        if l == 0:
            print("No racks selected. Quitting")
            return

        print pvs_start
        self.launch(pvs_start)
        self.monitor(pvs_stat)

    def launch(self, pvs_start):
        for start in pvs_start:
            print("Starting %s" % start)
            try:
                print("caput 1 to %s" % start)
                ca.caput(start, 1, wait=True)
            except Exception:
                print("Error setting %s" % start)
                continue

    def monitor(self, pvs_stat):
        done = False
        start_time = time.time()
        print pvs_stat
        while done is False:
            print("in while loop")
            print("before sleep")
            time.sleep(10) # sleep at start of loop to wait for status update
            print("after sleep")

            done = True # Start loop set to True
            if (time.time() - start_time) > TIMEOUT:
                print("Timeout while waiting for all racks to complete.")
                break
            #print("Before get stats")
            stat = ca.caget(pvs_stat)
            #print("stat %s" % stat)
            for i in stat:
                #print("stat element %i" % i)
                if i == RUNNING:
                    #print("stat element %i is RUNNING" % i)
                    done = False
                    break


def usage():
    print "python rf_batch_rack.py --fac <facility>"
    print "Example:'"
    print "python rf_batch_rack.py --fac LCLS'"


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Execute rack initialization in batch')

    parser.add_argument('-f', '--fac', dest='fac', choices=['B15', 'LCLS'],
                        help='Facility: DEV or LCLS', required=True)

    args = parser.parse_args()
    print args.fac

    racks=[]
    if args.fac == 'B15':
        racks.append('ACCL:L1B:0200:RACKA')
    elif args.fac == 'LCLS':
       print args.fac
       cms = ['ACCL:L0B:01', 
              'ACCL:L1B:02',
              'ACCL:L1B:03',
              'ACCL:L1B:H1',
              'ACCL:L1B:H2',
              'ACCL:L2B:04',
              'ACCL:L2B:05',
              'ACCL:L2B:06',
              'ACCL:L2B:07',
              'ACCL:L2B:08',
              'ACCL:L2B:09',
              'ACCL:L2B:10',
              'ACCL:L2B:11',
              'ACCL:L2B:12',
              'ACCL:L2B:13',
              'ACCL:L2B:14',
              'ACCL:L2B:15',
              'ACCL:L3B:16',
              'ACCL:L3B:17',
              'ACCL:L3B:18',
              'ACCL:L3B:19',
              'ACCL:L3B:20',
              'ACCL:L3B:21',
              'ACCL:L3B:22',
              'ACCL:L3B:23',
              'ACCL:L3B:24',
              'ACCL:L3B:25',
              'ACCL:L3B:26',
              'ACCL:L3B:27',
              'ACCL:L3B:28',
              'ACCL:L3B:29',
              'ACCL:L3B:30',
              'ACCL:L3B:31',
              'ACCL:L3B:32',
              'ACCL:L3B:33',
              'ACCL:L3B:34',
              'ACCL:L3B:35']

       rackids = ['A', 'B']
       for cm in cms:
           print cm
           for rackid in rackids:
               racks.append( "%s00:RACK%s" % (cm, rackid) )
    print "Racks: ", racks

    print("%s facility. Will execute rack initialization for selected racks" % args.fac)

    BatchControl(racks)
