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

# System modules
from time import sleep

# Custom modules
from utils.logger import log
from devices import sof
from templates.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==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
