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

# System modules
import requests
from urllib.parse import urlencode

# custom modules
from utils.logger import log
from devices import check


class Cabinet:
    '''Base wrapper class for the Siemens PLC switch 
     managing the Telescope cabinet.'''
    
    def __init__(self, url):
        '''Constructor.'''
        
        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 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 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):
        res = self.get("vstatus")
        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):
        res = self.all["Cabinet"]
        self._state = True if res == 'ON' else False
        return self._state

    @state.setter
    def state(self, s):
        start_stop = "on" if s else "off"
        params = {"startstop": start_stop}
        self.put("apikey=bigrip", params=params)
        self._state = self.state
