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

# System modules
import contextlib
import time
from time import sleep

# Third-party modules
from astropy.time import Time

# Other templates
from ..config.constants import camera_state, frame_number
from ..devices import cam
from ..utils import check
from ..utils.logger import log
from .basetemplate import BaseTemplate


class Template(BaseTemplate):
    def __init__(self):
        super().__init__()
        self.name = __name__
        self.description = "Test template"

    @check.content_errors
    def content(self, params):

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

        try:
            repeat = 10  # params.get("repeat") or 10
        except KeyError as e:
            log.error(f"Parameter {e} not found")

        ################
        ##### test #####
        ################

        for i in range(repeat):

            log.debug("Start iteration")
            log.debug(f"Abort flag: {self.aborted}")

            if self.check_pause_or_abort():
                log.debug(f"Abort flag: {self.aborted}")
                log.debug("check True")
                return

            log.debug(f"Abort flag: {self.aborted}")

            try:
                cam.start(10, 1, datetime=Time.now())
            except Exception as e:
                log.error("An error occurred!")
                log.error(e)
                return

            # Some debug time counter
            now = Time.now()

            # Checking if the exposure is still running
            while cam.state != 0:
                res = self.check_pause_or_abort()
                log.debug(f"Abort flag: {self.aborted}")
                log.debug(f"check_pause_or_abort returned {res}")

                if res:
                    log.debug("check_pause_or_abort returned true. I'm here")
                    return

                status = int(cam.state)
                if status == 5:  # i.e. error in camera
                    log.error(f"Camera {camera_state[status]}")
                    return
                else:
                    elapsed = (Time.now() - now).sec
                    log.info(
                        f"Camera {
                            camera_state[status]}, elapsed {elapsed}")
                    sleep(0.5)

            log.debug(f"-------------repeat {i}")
