

import sys
import Ice
import logging
from cysystemd import journal as cyjournal
import sharknir


def testOB_tracking(ins_s=None, det_s=None, tel_s=None, **kwargs):
    shins_root = os.environ["SHINS"]
    logger = logging.getLogger(__name__)
    logger.setLevel(level=logging.DEBUG)

    formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s')

    cyjournal_handler = cyjournal.JournaldLogHandler()
    cyjournal_handler.setFormatter(formatter)

    logger.addHandler(cyjournal_handler)
    logger.info('SHINS:testOB_tracking: begin')

    if ins_s:
        print('Instrument setup: ')
        logger.info('Instrument setup: ')
        for s in ins_s:
            print('\t {} = {}'.format(s, ins_s[s]))
            logger.info(' {} = {}'.format(s, ins_s[s]))
        ins_sup = ins_s
    if det_s:
        print('Detector setup: ')
        logger.info('Detector setup: ')
        for s in det_s:
            print('\t {} = {}'.format(s, det_s[s]))
            logger.info(' {} = {}'.format(s, det_s[s]))
        det_sup = det_s
    if tel_s:
        print('Telescope setup: ')
        logger.info('Telescope setup: ')
        for s in tel_s:
            print('\t {} = {}'.format(s, tel_s[s]))
            logger.info(' {} = {}'.format(s, tel_s[s]))
            # print('\t',s,'=',tel_s[s]) # py3
        tel_sup = tel_s

    status = 0
    ic = None  # Ice Communicator
    try:
        ic = Ice.initialize(sys.argv)
        base = ic.stringToProxy("ObsControlAdapterSeq:default -p 10500")
        obsController = sharknir.obsControl.SequencerPrx.checkedCast(base)

        if (not obsController):
            raise RuntimeError("Invalid Proxy")

        try:
            # Tracking device setup: derot needs to be set up to specific position,
            # not a named position. Extracting key and value from instrument setup
            # dictionary.

            wanted_keys = ['DROT_PosAng']
            align_ins_s = dict((k, float(ins_s[k])) for k in wanted_keys if k in ins_s)

            # logging
            for s in align_ins_s:
                print(' {} = {}'.format(s, align_ins_s[s]))
                logger.info(' {} = {}'.format(s, align_ins_s[s]))

            logger.info("Setting up derotator")

            # setting up
            # status = obsController.setupInstrumentAbsoluteStepsStart(align_ins_s)
            status = obsController.setupInstrumentAbsolutePositionStart(align_ins_s, Ice.Unset)
            time_out = 60000  # Ice.Unset [in milliSeconds]
            # status = obsController.setupInstrumentAbsoluteStepsWait(align_ins_s, time_out)
            status = obsController.setupInstrumentAbsolutePositionWait(align_ins_s, Ice.Unset)
            logger.info("Initilizing tracking devices ... ")
            # status = obsController.initTracking()
            logger.info("DONE")
            T = timer.timer()
            T.begin()
            elapsedSecs = 1
            logger.info("Start tracking trajectory ... ")
            status = obsController.trackingStart()
 
            logger.info("Waiting {} millisec ...".format(time_out))
            while (T.elapsed() < time_out/1000.):
                if T.elapsed > elapsedSecs:
                    elapsedSecs +=1
                else:
                    timer.time.sleep(0.1)

            logger.info("Stop tracking devices ... ")
            status = obsController.trackingStop()
            logger.info("DONE")

        except AttributeError as e:
            status = obsController.trackingStop()
            raise AttributeError
        except StandardError as e:
            logger.error(e)
            status = obsController.trackingStop()
            raise e


        except KeyboardInterrupt as e:
            sys.exit()

        else:
            pass
            ##
            ##
            ##{ item_description }
            ##

    except KeyboardInterrupt as e:
        sys.exit()

    except:
        #traceback.print_exc()
        status = 1

    if ic:
        # Clean up
        try:
            ic.destroy()
        except:
            #traceback.print_exc()
            status = 1
            print('testOB_tracking: end')
            logger.info('testOB_tracking: end')
