import time
from . import simple


class MQTTClient(simple.MQTTClient):

    DELAY = 2
    DEBUG = False
    is_connected = False

    def log(self, in_reconnect, err):
        """Log error if DEBUG is True"""
        if self.DEBUG:
            if in_reconnect:
                print("mqtt reconnect: %r" % err)
            else:
                print("mqtt: %r" % err)

    def reconnect(self):
        """Try to connect or reconnect to MQTT broker"""
        i = 0
        while 1:
            try:
                self.is_connected = True
                return super().connect(False)
            except OSError as err:
                self.is_connected = False
                self.log(True, err)
                i += 1
                time.sleep(self.DELAY)
            if i >= 5:
                print("Mqtt reconnect : too much retry")
                self.is_connected = False
                break


    def publish(self, topic, msg, retain=False, qos=0):
        """Try to publish if connected to MQTT broker"""
        if self.is_connected:
            i = 0
            while 1:
                try:
                    return super().publish(topic, msg, retain, qos)
                except OSError as e:
                    i += 1
                    self.log(False, e)
                if i >= 5:
                    print("Mqtt publish : too much retry")
                    self.is_connected = False
                    break
                else:
                    self.reconnect()
        else:
            print("Mqtt publish: not connected")

    def wait_msg(self):
        """Check if any subscribed messages is available"""
        if self.is_connected:
            i = 0
            while 1:
                try:
                    return super().wait_msg()
                except OSError as e:
                    i += 1
                    self.log(False, e)
                if i >= 5:
                    print("Mqtt wait_msg : too much retry")
                    self.is_connected = False
                    break
                else:
                    self.reconnect()
        else:
            print("Mqtt wait_msg: not connected")
