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

# System modules
from time import sleep

# Custom modules
from utils.logger import log
#from utils.coordinates import to_radec
from devices import dom, tel

# Other templates
from templates.basetemplate import BaseTemplate
from templates.fillheader import Template as FillHeader


class Template(BaseTemplate):
    def __init__(self):
        super().__init__()
        self.name = "acquisition"
        self.description = "Moves telescope to specific coordinates"

    def content(self, params):

        ########################
        ##### 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

        # 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.
        tol = 5.0  # deg of az tolerance between telescope and dome
        while dom.is_moving or abs(dom.azimuth-tel.altaz[1]) > 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)

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

        return
