
from shinsapp import SHINSApp
from util.shinsLogger import logger
from util import variables as uvars
from util import functions as ufun
from util import exception
import numpy as np
from alignment.allineamento import Align_the_coronagraph as aly

from SHARKNIR_gen_base import SHARKNIR_gen_base

class SHARKNIR_cal_tec_NCPA_wollaston(SHINSApp):

    @exception.handler_for_run
    def run(self, ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs):
        '''Calculate NCPA with wollaston using star.
        '''

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

        self.gen_base = SHARKNIR_gen_base();        gen_base = self.gen_base

        fitsDir = uvars.fitsDir + obsController.getCurrentDataDirectory() +'/'

        #############################################
        # START AND WAIT INSTRUMENT AND SASHA SETUP #
        #############################################

        gen_base.main(ins_s=ins_s, det_s=det_s, expose=False)

        self.master_array = [] # the list of images CDS-subtracted and meaned over NREADS=10

        # Apo positions are shared between focus and defocus loops
        several_apos = ["HOLE3", "Lens_PD_neg", "Lens_PD_pos"]

        #############################
        # First LOOP (FOCUSED STAR) #
        #############################
        
        several_groups = ["3",  "3",  "3"]
        several_reads =  ["2",  "2",  "1"]
        several_drops =  ["70", "28", "74"]
        several_readouts = ["PD_wollaston_stripe_small", "PD_wollaston_stripe_small", "PD_wollaston_stripe_large"]
    
        logger.info("***Starting Focused star")
        for apo, group, read, drop, readout in zip(several_apos, several_groups, several_reads, several_drops, several_readouts):
            
            ins_s = {
                "APODIZER_W": apo,
            }
            
            det_s.update({
                "NGROUPS": group, 
                "NREADS": read,
                "NDROPS": drop,
                "READOUT": readout,
            })
            
            logger.info("****Start focus setup and image")
            self.status, self.filename, self.other = gen_base.main(ins_s, det_s)
            logger.info("****End focus setup and image")

            if self.paragraph("Focused {}".format(apo)):
                
                self.master_array = ufun.ncpa_masterize(fitsDir, self.filename, self.master_array)

        ##################
        # PAUSE / RESUME #
        ##################

        self.paused = True
        logger.warning("Resume when ready")
        self.check_pause_or_abort()
        
        ################################
        # Second LOOP (DEFOCUSED STAR) #
        ################################
    
        several_groups = ["3",  "2",  "9"]
        several_reads =  ["1",  "6",  "1"]
        several_drops =  ["6", "160", "22"]
        
        logger.warning("Starting Defocused star")
        for apo, group, read, drop in zip(several_apos, several_groups, several_reads, several_drops):
            
            ins_s = {
                "APODIZER_W": apo,
            }
            
            det_s.update({"NGROUPS": group, 
                          "NREADS": read,
                          "NDROPS": drop,
                          })
            
            logger.info("****Start defocus setup and image")
            self.status, self.filename, self.other = gen_base.main(ins_s, det_s)
            logger.info("****End defocus setup and image")
            
            if self.paragraph("Defocused {}".format(apo)):
                
                self.master_array = ufun.ncpa_masterize(fitsDir, self.filename, self.master_array)

        ########################################
        # ONERA CODE in IDL, using IDL bridges #
        ########################################            
        if self.paragraph("ONERA processing"):

            ufun.call_onera(self.master_array)

            # Print Strehl
                    
            saly = aly(camera='HAWAII H-2RG')
            saly.PSFNoCoro.LoadImage(self.master_array[0])
            strehl = saly.PSFNoCoro.getStrehl(0.0145, method='esposito',
                                          wavelengthInUm=1.593, Dpup=8.22*0.98, eps=0.1,
                                          verbose=False, returnSR=True)
            
            logger.info("Strehl ratio: {:.2}".format(strehl))
