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

# System modules
import sys

# Custom modules
from utils.logger import log
from devices import cam, tel, sof
from config.constants import camera_state, filter_state
from time import sleep


class BaseTemplate:
    '''Base template. Other themplates inherit from this, by filling up
       the "content" method.'''

    def __init__(self):
        '''Contructor'''

        #self.name = type(self).__name__
        self.name = __name__
        self.description = "Other templates inherit from this"
        self.error = []
        self.paused = False
        self.aborted = False
        self.filename = ""
        self.filenames = []

    # Exception decorator does NOT go here
    def content(self):
        '''
        Here the inherited template will be developed
        '''

    # Exception decorator goes here
    def run(self, params, extra={}):
        '''
        Check the params and run the content method.
        '''

        log.info(f"Running template {self.name}")

        if not params:
            log.warning(f"Params are empty: {params}")
        else:
            log.debug(f"Params:")
            for key, value in params.items():
                log.debug(f"{key:>10}  {str(value):<6}")

        log.info(f"Running content {self.name}")
        self.content(params)

        log.info(f"Template {self.name} ended")

    def check_pause_or_abort(self):
        '''
        Pause/Resume the execution of the template.
        '''

        if self.paused:
            log.warning("Paused!")
        # else:
        #     log.debug("Resume!")

        if self.aborted:
            log.debug("Abort!")
            self.abort()

        while self.paused:
            sleep(0.1)
            if self.aborted:
                self.abort()
                break

    def abort(self):
        '''
        Abort this the template.
        '''

        msg = f"Aborting template {self.name}"
        log.error(msg)
        self.error.append(msg)

        try:
            if sof.state:
                # To be checked:
                # if the camera is off, here cam.state=[],
                # while in ipython cam.state=None
                if (cam.state != 0) or (cam.is_moving != 0):
                    log.warning(f"Camera is {camera_state[cam.state]}")
                    log.warning(f"Filter is {filter_state[cam.is_moving]}")
                    log.error(f"Aborting camera.")
                    cam.abort()

        except Exception as e:
            msg = f"Interrupt triggered in {__name__}"
            log.error(msg)
            log.error(e)
            self.error.append(msg)
            self.error.append(e)

        sys.exit(1)
        return
