
import hashlib

import hue.lights


class Device(object):

    TYPE_HUE = 0

    STATE_UNKNOWN = -1
    STATE_OFF = 0
    STATE_ON = 1

    def __init__(self, dev_type, dev_id):
        self.dev_type = dev_type
        self.dev_id = dev_id
        self.guid = make_guid(dev_type, dev_id)
        self.state = Device.STATE_UNKNOWN

    def get_name(self):
        pass

    def get_type(self):
        pass

    def refresh(self):
        pass


class HueDevice(Device):

    def __init__(self, hue_id):
        super(HueDevice, self).__init__(Device.TYPE_HUE, hue_id)
        self.name = None

    def get_type(self):
        return 'Hue'

    def get_name(self):
        return self.name if self.name else self.dev_id

    def refresh(self):
        status = hue.lights.getStatus(self.dev_id)
        if status:
            self.state = Device.STATE_ON \
                if status['state']['on'] == True else Device.STATE_OFF
            self.name = status['name']
        else:
            self.state = Device.STATE_UNKNOWN


def make_guid(dev_type, dev_id):
    m = hashlib.md5()
    m.update('{0}_{1}'.format(dev_type, dev_id))
    return m.hexdigest()


def factory(dev_type, dev_id):
    if dev_type == Device.TYPE_HUE:
        return HueDevice(dev_id)
