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

# System modules
from urllib.parse import urlencode

# Third-party modules
import requests

# Other templates
from ..utils import check
from ..utils.logger import log


class Sonoff:
    def __init__(self, url, id):
        self.url = url
        self.addr = self.url + "/json.htm"
        self.timeout = 3
        self.error = None
        self.id = id
        requests.packages.urllib3.disable_warnings()  # For verify=False

    @check.request_errors
    def get(self, param=None, id=None):
        return
        base_params = {"type": "devices"}
        if id:
            base_params.update({"rid": id})

        res = requests.get(self.addr,
                           params=base_params,
                           timeout=self.timeout,
                           verify=False)

        res.raise_for_status()
        resj = res.json()
        if resj["status"] != "OK":
            log.error(f'DOMOTICS: {resj["status"]}')
            if "message" in resj:
                log.error(resj["message"])
        else:
            try:
                if not param:
                    return resj
                else:
                    if param == "ServerTime":
                        value = resj["ServerTime"]
                    else:
                        value = resj["result"][0][param]
                    return value
            except AttributeError as e:
                return res
            except KeyError as e:
                return res

    @check.request_errors
    def put(self, params={}, id=None):
        return
        base_params = {"type": "command", "idx": id}
        params.update(base_params)
        res = requests.get(self.addr,
                           params=params,
                           timeout=self.timeout,
                           verify=False)

        res.raise_for_status()
        resj = res.json()
        if resj["status"] != "OK":
            log.error(f'DOMOTICS: {resj["status"]}')
            if "message" in resj:
                log.error(resj["message"])

    @property
    def clock(self):
        local = self.get("ServerTime")  # Local time
        return local

    @property
    def last_update(self):
        res = self.get("LastUpdate", id=self.id)
        return res

    @property
    def name(self):
        res = self.get("Name", id=self.id)

    @property
    def all(self):
        res = self.get()
        return res


class Switch(Sonoff):
    def __init__(self, url, id):
        super().__init__(url, id)

    def reboot(self):

        while self.state:
            self.state = False

        while not self.state:
            self.state = True

        return self.state

    @property
    def state(self):
        res = self.get("Status", id=self.id)
        self._state = True if res == 'On' else False
        return self._state

    @state.setter
    def state(self, s):
        switchcmd = 'On' if s else 'Off'
        params = {"param": "switchlight", "switchcmd": switchcmd}
        res = self.put(params, id=self.id)
        self._state = self.state


class Sensor(Sonoff):
    def __init__(self, url, temp_id, hum_id):
        super().__init__(url, temp_id)
        self.id = temp_id  # recycle for last_update
        self.hum_id = hum_id

    @property
    def temperature(self):
        res = self.get("Temp", id=self.id)
        return res

    @property
    def humidity(self):
        res = self.get("Humidity", id=self.hum_id)
        return res
