#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# System modules

# Third-party modules
from astropy.io import fits
from astropy.time import Time

# Custom modules
from config.constants import temp_fits
from devices import dom
from utils.analysis import skyflat_exptime
from utils.logger import log

# Other templates
from templates.acquisition import Template as Acquisition
from templates.basetemplate import BaseTemplate
from templates.observation import Template as Observation


class Template(BaseTemplate):
    """Sky flat template"""
    
    def __init__(self):
        """Constructor"""
        super().__init__()
        self.name = "skyflat"
        self.description = "Takes a set of sky flat calibrations"

    def content(self, params):
        """Template implementation"""

        ########################
        ##### Params check #####
        ########################

        try:
            binning = params["binning"]
            repeat = params.get("repeat") or 1
            filt = params["filter"]
            exptime = params["exptime"]
        except KeyError as e:
            log.error(f"Parameter {e} not found")

        fixed = {
            "objname": "Sky flat frame",
            "frametype": "Flat"
        }

        params.update(fixed)


        ############################
        ##### Moving telescope #####
        ############################
        
        # hour < 12: 'twilight', hour > 12: 'dawn'
        now = Time.now()
        hour = now.datetime.hour

        # Point opposite to the Sun:
        # West if twilight, Est if dawn.
        altaz = [30, 270] if hour < 12 else [30, 90]
            
        acq = Acquisition()
        acq.run({"altaz": altaz })
        self.check_pause_or_abort()
        
        ###################################
        ##### Taking a test flat image ####
        ###################################

        obs = Observation()
        obs.run(params)
        self.check_pause_or_abort()

        # Calculating the average count rate 
        img = fits.getdata(temp_fits)
        average_counts = img.data.mean()
        rate = average_counts / exptime # calcolo test rate (counts/(s*pixel))
    
        # Retrieving optimal exptimes "à la Tyson&Gal" 
        exptimes = skyflat_exptime(rate, binning=binning, repeat=repeat)

        ####################################################
        ##### Taking sky flats looping optimal exptimes ####
        ####################################################

        for exp in exptimes:
            self.check_pause_or_abort()

            params["exptime"] = exp
            obs.run(params)

        
        return
