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

# System modules
import sys
from time import sleep

# Third-party modules
from astropy.io import fits

# Other templates
from ..devices import sof
from ..utils.logger import log
from .basetemplate import BaseTemplate


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

    def content(self, params):

        ########################
        ##### Params check #####
        ########################
        try:
            getstatus = params.get("getstatus")
            setstatusto = params.get("setstatusto")
        except KeyError as e:
            log.error(f"Parameter {e} not found")

        ########################
        #####      GET     #####
        ########################

        if getstatus == 1:
            log.info(f"Sonoff is {sof.state}")

        ########################
        #####      SET     #####
        ########################

        if setstatusto is None:
            return

        if setstatusto == 0:
            sof.state = "Off"
            sleep(0.2)
            if (sof.state != "Off"):
                log.error(f"Failed to switch off the Sonoff!")
            else:
                log.info(f"Sonoff is now off")
            return

        if setstatusto == 1:
            sof.state = "On"
            sleep(2)
            if (sof.state != "On"):
                log.error(f"Failed to switch on the Sonoff!")
            else:
                log.info(f"Sonoff is now on")
            return

        return
