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

# System modules
from urllib.parse import urlencode

# Third-party modules
import requests

# Custom modules
from utils import check
from utils.logger import log


class Switch:
    '''Base wrapper class for the Siemens PLC switch 
     managing the Telescope cabinet.'''

    def __init__(self, url, id=0):
        '''Constructor. id for compatibility with other switches'''

        self.id = id
        self.url = url
        self.addr = self.url
        self.timeout = 3
        self.error = None

    @check.request_errors
    def get(self, method):
        '''Send a HTTP GET request to request information
        from the device address.'''
        
        res = requests.get(f"{self.addr}/{method}",
                           timeout=self.timeout)
        res.raise_for_status()
        try:
            return res
        except AttributeError as e:
            return res
        except KeyError as e:
            return res

    @check.request_errors
    def put(self, method, params={}):
        '''Send a HTTP GET request to put information 
        at the device address.'''
        
        res = requests.get(f"{self.addr}/{method}",
                           params=params,
                           timeout=self.timeout)
        res.raise_for_status()
        return res

    @property
    def all(self):
        '''Requesting all the avaible status information.'''
        
        res = self.get("vstatus")
        if not self.error:
            vstatus = res.text.split("<br>")[:-1]  # cutting last empty line
            vdict = dict([v.split(" is ") for v in vstatus])
            return vdict        

    @property
    def state(self):
        '''Requesting just the state information: the cabinet is on or off?'''
        
        res = self.all
        
        if not res:
            return res
        
        self._state = True if res["Cabinet"] == 'ON' else False
        return self._state

    @state.setter
    def state(self, s):
        '''Switch the on/off state of the cabinet.'''
        
        start_stop = "on" if s else "off"
        params = {"startstop": start_stop}
        # params = {"tstart": start_stop} # Temp 17h
        self.put("apikey=bigrip", params=params)
        self._state = self.state
