import time
import numpy as np
from shinsapp import SHINSApp
from util.shinsLogger import logger
from util import variables as uvars
from util import exception
from util import functions as ufun
from astropy.time import Time, TimeDelta

from SHARKNIR_gen_base import SHARKNIR_gen_base

class SHARKNIR_lss_obs(SHINSApp):
    """calibration
    """

    @exception.handler_for_run
    def run(self, ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs):

        logger.info(__name__)
        obsController = self.obsController
        self.status = uvars.EXIT_SUCCESS

        gen_base = SHARKNIR_gen_base()

        ###########################
        # CHECK IF LOOP IS CLOSED #
        ###########################
        status, is_loop_closed = obsController.RTCTTRead(uvars.TTControlLoopEna, 1, "dsp")
        is_loop_closed = is_loop_closed[0]
        logger.info("Is loop closed? {}".format(is_loop_closed))

       

        drotMode    = ins_s["DROT_Mode"]
        posAng      = float(ins_s["OBS_PosAng"])
        steps       = 1#int(ins_s["STEPS"])
        offsetAng   = 10

        for i in range(steps):

            self.paragraph("Iteration {} of {}".format(i+1, steps))

            ##############################
            # INSTRUMENT AND SASHA SETUP #
            ##############################
            if self.paragraph("INSTRUMENT AND SASHA SETUP"):
                logger.info("Begin Instrument and SASHA setup")
                print("INS_S : {}".format(ins_s))
                print("DET_S : {}".format(det_s))
                gen_base.main(ins_s=ins_s, det_s=det_s, expose=False)
                logger.info("Instrument and SASHA setup completed")

            ################################
            # START FIELD-FIXED DEROTATION #
            ################################    
            if self.paragraph("START {} Derotation at PosAngle = {} deg".format(drotMode, posAng)):
                dateMjd = Time.now()
                logger.info("Wait for Derotationt to start ... ")
                async_drot = obsController.begin_trackingStart2(dateMjd.mjd, posAng)
                # status = obsController.trackingStart2(dateMjd.mjd, posAng)
                logger.info("Wait for Derotationt to start ... DONE")

            # ##################
            # # PAUSE / RESUME #
            # ##################
            
            # self.paused = True
            # logger.warning("Resume when Derotation is ready to start tracking; Quit otherwise.")
            # print("(R)esume, (Q)uit")
            
            # import sys
            # from select import select
            
            # timeout = 2
            
            # answer = None
            # print("Enter something:"),
            # self.paused = True
        
    
            # while self.paused==True and self.aborted==False:
                
            #     rlist, _, _ = select([sys.stdin], [], [], timeout)
            #     if rlist:
            #         answer = sys.stdin.readline()
            #         print(answer)
            #     else:
            #         print("still waiting...")
                
            #     if answer:
            #         if answer.lower().startswith('r'):
            #             self.paused = False
            #             pass
            #         if answer.lower().startswith('q'):
            #             self.paused = False
            #             self.aborted = True
            #             self.abort()
            #             return
            #         else:
            #             pass
                    
            ########################
            # BEGIN EXPOSING SASHA #
            ########################
            if self.paragraph("BEGIN IMAGE ACQUISITION"):
                sashaWaitTime = 30
                logger.debug("Wait {} sec for tracking to start before start acquiring".format(sashaWaitTime))
                time.sleep(sashaWaitTime)
                logger.info("Waiting camera exposure to begin ...")
                acquisition_completed = False
                async_sashaExpose = obsController.begin_sashaExpose()
                logger.info("Waiting camera exposure to begin ... DONE")
                
            ######################
            # END EXPOSING SASHA #
            ######################
            if self.paragraph("END IMAGE ACQUISITION"):
                logger.info("Waiting camera exposure to complete ...")
                self.status, self.filenames = obsController.end_sashaExpose(async_sashaExpose)
                logger.info("Waiting camera exposure to complete ... DONE")
                acquisition_completed = True
                logger.info("FITS files are "+str(self.filenames))
                
            ##############################
            # END FIELD-FIXED DEROTATION #
            ##############################
            if self.paragraph("END DEROTATION"):
                if acquisition_completed:
                    logger.info("Image acquisition is completed, stop derotation now")
                    async_drot_stop = obsController.begin_trackingStop()
                    self.status = obsController.end_trackingStop(async_drot_stop)
                    waitTime = 5
                    logger.debug("Wait {} sec for Derotation to Stop".format(waitTime))
                    time.sleep(waitTime)
                    logger.info("Derotation Stopped")
                else:
                    logger.debug("Derotation about to terminate before image acquisition in completed")
                    logger.debug("Wait for Derotationt to end ... ")
                    self.status = obsController.end_trackingStart2(async_drot)
                    logger.debug("Wait for Derotationt to end ... DONE")

            # ##################
            # # PAUSE / RESUME #
            # ##################
            
            # self.paused = True
            # logger.warning("Resume when tracking has stopped; Quit otherwise.")
            # print("(R)esume, (Q)uit")
            
            # import sys
            # from select import select
            
            # timeout = 2
            
            # answer = None
            # print("Enter something:"),
            # self.paused = True
            
            
            # while self.paused==True and self.aborted==False:
                
            #     rlist, _, _ = select([sys.stdin], [], [], timeout)
            #     if rlist:
            #         answer = sys.stdin.readline()
            #         print(answer)
            #     else:
            #         print("still waiting...")
                    
            #     if answer:
            #         if answer.lower().startswith('r'):
            #             self.paused = False
            #             pass
            #         if answer.lower().startswith('q'):
            #             self.paused = False
            #             self.aborted = True
            #             self.abort()
            #             return
            #         else:
            #             pass


            ##############################
            # INSTRUMENT AND SASHA SETUP #
            ##############################
            # if self.paragraph("INSTRUMENT AND SASHA SETUP + IMAGES FOR SPECKLES ACQUISITION"):
            #     ndit = int(det_s["NDIT"])/2
            #     det_s_speckles = det_s.copy()
            #     det_s_speckles["NDIT"] = str(ndit)

            #     ins_s_speckles = ins_s.copy()

            #     ####################
            #     # GET CURRENT DROT #
            #     ####################
            #     minDrotPos, maxDrotPos = [1, 180] #[74.6, 181.6]
            #     logger.debug("Retriving Drot Position")
            #     inDict = {"DROT":-9999.9}
            #     unit = "DEGREE"
            #     self.status, drotDict = self.obsController.getPosition(unit, inDict)
            #     drotPos = drotDict["DROT"]
            #     logger.info("DROT pos : {} deg".format(drotPos))
                
            #     newDrotPos = drotPos+offsetAng if drotPos+offsetAng < maxDrotPos else drotPos-offsetAng
            #     ins_s_speckles["DROT_PosAng"] = str(newDrotPos)
            #     ins_s_speckles["DROT_Mode"] = "PUPIL"
                
            #     logger.info("Begin Instrument and SASHA setup")
            #     print("INS_S : {}".format(ins_s))
            #     print("DET_S : {}".format(det_s))
            #     gen_base.main(ins_s=ins_s_speckles, det_s=det_s_speckles)
            #     logger.info("Instrument and SASHA setup completed")

            logger.debug("End Of Iteration")


              
            ###############################
            # STOP FIELD-FIXED DEROTATION #
            ###############################
            if self.paragraph("STOP DEROTAION"):
                logger.info("Stop derotation the ... ")
                status = obsController.trackingStop()
                logger.info("Stop derotation the ... DONE")

        logger.info("Lss Obs ENDED")
