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

# System modules
from time import sleep

# Other templates
from ..devices import dom, tel
from ..utils.logger import log
from .basetemplate import BaseTemplate
from .fillheader import Template as FillHeader


class Template(BaseTemplate):
    """Acquisition template"""

    def __init__(self):
        """Constructor"""

        super().__init__()
        self.name = "acquisition"
        self.description = "Moves telescope to specific coordinates"

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

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

        try:
            radec = params.get("radec")
            altaz = params.get("altaz")

        except KeyError as e:
            log.error(f"Parameter {e} not found")

        #######################
        ##### Dome slaved #####
        #######################

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

        ############################
        ##### Moving telescope #####
        ############################

        # Equatorial coordinates
        if radec:
            # Enable tracking
            while tel.tracking != True:
                log.debug(f"Telescope tracking still {tel.tracking}")
                tel.tracking = True
            log.debug(f"Telescope tracking is now {tel.tracking}")
            # Slew to ra, dec
            tel.targetradec = radec
            sleep(0.2)
            tel.track()
            msg = "Moving!"

        # Horizontal coordinates
        elif altaz:
            # Slew to alt, az
            tel.altaz = altaz
            log.warning("Moving!")

        # No coordinates
        else:
            log.error("Provide radec or altaz parameters.")
            return

        log.debug("Moving the telescope")
        # Moving the telescope
        while tel.is_moving != 8:  # 8 is astelco stop?
            log.debug(f"Tel Moving? {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)
            if self.check_pause_or_abort():
                log.debug("check_pause_or_abort returned true. I'm here")
                return

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

        # Waiting for the dome, normally is the slowest.
        tol = 5.0  # deg of az tolerance between telescope and dome
        while dom.is_moving \
                or abs(dom.azimuth - tel.altaz[1]) > tol \
                or abs(dom.azimuth - tel.altaz[1]) - 360 > tol:

            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)
            if self.check_pause_or_abort():
                log.debug("check_pause_or_abort returned true. I'm here")
                return

        log.info(f"Dome is moving? {dom.is_moving}")

        return
