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

# System modules
from time import sleep

# Custom modules
from config.constants import dome_park_position, telescope_flat_position
from devices import dom, tel
from utils.logger import log

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


class Template(BaseTemplate):
    """Dome flat template"""
    
    def __init__(self):
        """Constructor"""
        super().__init__()
        self.name = "domeflat"
        self.description = "Takes a set of dome 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": "Dome flat frame",
            "frametype": "Flat"
        }

        params.update(fixed)

        #################################
        ##### Dome unslave and park #####
        #################################

        while dom.slave == True:
            log.debug(f"Dome slaving still {dom.slave}")
            dom.slave = False
        log.debug(f"Dome slaving is now {dom.slave}")

        dom.park()

        ############################
        ##### Moving telescope #####
        ############################
        
        # Disable tracking
        while tel.tracking == True:
            log.debug(f"Telescope tracking still {tel.tracking}")
            tel.tracking = False
            log.debug(f"Telescope tracking is now {tel.tracking}")

        # Slew to alt, az
        tel.altaz = telescope_flat_position
        log.warning("Moving!")

        # Moving the telescope
        while tel.is_moving:
            msg = f"radec: {tel.radec[0] :.2f} {tel.radec[1] :.2f} "
            msg += f"altaz: {tel.altaz[0] :.2f} {tel.altaz[1] :.2f} "
            log.warning(msg)
            sleep(0.2)

        log.info(f"Telescope is tracking? {tel.tracking}")

        # Waiting for the dome, normally is the slowest.
        tolerance = 2.0  # deg of az tolerance between telescope and flat screen
        
        dom.park()
        
        # Here, telescope azimith does not to be the same as dome azimuth!
        while dom.is_moving \
              or not abs(tel.altaz[0]-telescope_flat_position[0]) < tolerance \
              or not abs(tel.altaz[1]-telescope_flat_position[1]) < tolerance \
              or not abs(dom.is_parked):
            
            self.check_pause_or_abort()

            msg = f"Dome is moving? {dom.is_moving}. "
            msg += f"Dom az {dom.azimuth :.2f}, "
            msg += f"Tel az {tel.altaz[1] :.2f}"
            log.warning(msg)
            sleep(0.5)

        log.info(f"Dome is moving? {dom.is_moving}")
        
        ##################################
        ##### Calling Observation tpl ####
        ##################################

        obs = Observation()
        obs.run(params)

        return
