__author__ = 'butzel'
__license__ = "GPLv3: https://www.gnu.org/licenses/gpl-3.0.en.html"
__version__ = "0.2"


class LCD_RGB_Backlight(object):
    """ this class represents the 'Grove LCD RGB Backlight'
        from seeedstudio
        Note: the LCD needs a 5V power on VCC
        otherwise the LCD will not work
    """

    def __init__(self, i2c, i2c_addr_lcd=0x3E, i2c_addr_rgb=0x62):
        """
        Initialize the Grove LCD RGB Backlight
        i2c: machine.I2C
        i2c_addr_lcd = I2C-Address of LCD (0x3e)
        i2c_addr_rgb = I2C-Address of RGB-Backlight LED (0x62)
        """
        self._rgb = i2c_addr_rgb
        self._lcd = i2c_addr_lcd
        self._i2c = i2c
        self._set = 0x4  # LCD ON
        self._typ = 0x8  # 0=1Line,4=5x10px, 8=2Line,16=8bit-lcd for cmd_func
        self._cmd = b"\x80"  # Command
        self._dat = b"\x40"  # Data

        self._cmd_cls = 0x1
        self._cmd_home = 0x2
        self._cmd_entry = 0x4
        self._cmd_set = 0x8   # Display settings self._set
        self._cmd_csrs = 0x10  # Cursor Shift
        self._cmd_func = 0x20  # Display Function: DataLen, Lines, Font

        # initialize LCD   # wait for power rises to 4.5V
        __import__("time").sleep(.045)
        self._lcdCMD(self._cmd_func | self._typ)
        __import__("time").sleep(.0045)
        self._lcdCMD(self._cmd_func | self._typ)
        __import__("time").sleep(.0012)
        self._lcdCMD(self._cmd_func | self._typ)

        # settings
        self._lcdCMD(self._cmd_set | self._set)
        self.clear()

        # EntryMode:
        self._lcdCMD(self._cmd_entry | 0x02)

        # initialize RGB-Backlight:
        self._i2c.writeto(self._rgb, b"\x00\x00")
        self._i2c.writeto(self._rgb, b"\x08\xFF")
        self._i2c.writeto(self._rgb, b"\x01\x00")

    def bl_on(self):
        # re-initialize RGB-Backlight
        self._i2c.writeto(self._rgb, b"\x00\x00")
        self._i2c.writeto(self._rgb, b"\x08\xFF")
        self._i2c.writeto(self._rgb, b"\x01\x00")
        self.bl_color(255, 255, 255)

    def bl_off(self):
        self.bl_stopblink()
        self.bl_color(0, 0, 0)

    def bl_color(self, red=0, green=0, blue=0):
        """
        set the Backlight Color
        red: red-color-value
        green: green color value
        blue: blue color value
        """
        self._i2c.writeto(self._rgb, b"\x04" + chr(red % 256))
        self._i2c.writeto(self._rgb, b"\x03" + chr(green % 256))
        self._i2c.writeto(self._rgb, b"\x02" + chr(blue % 256))

    def bl_blink(self, duty=127, speed=24):
        """
        let the Backlight blink
        duty: enabled  0 = stop blinking, 1=short, 255 = full
        speed: frq
        """
        if not duty:
            return self.bl_stopblink()
        self._i2c.writeto(self._rgb, b"\x01\x20")
        self._i2c.writeto(self._rgb, b"\x07" + chr(speed))
        self._i2c.writeto(self._rgb, b"\x06" + chr(duty))

    def bl_stopblink(self):
        """
        stop blinking Backlight
        """
        self._i2c.writeto(self._rgb, b"\x07\x00")
        self._i2c.writeto(self._rgb, b"\x06\xff")
        self._i2c.writeto(self._rgb, b"\x01\x00")

    def cursorMode(self, cursor=0):
        """
        set the cursor mode:
        cursor =  0  = off
                  -1/1  = blink off/on
                  -2/2  = underscore off/on
        """
        if cursor > 0:
            cursor = cursor % 4
            self._set |= cursor
        elif cursor < 0:
            self._set &= ~(abs(cursor) % 4)
        else:
            self.cursorMode(-1)
            self.cursorMode(-2)
        self._lcdCMD(chr(self._cmd_set | self._set))

    def clear(self):
        """
        clear LCD-Screen
        """
        self._lcdCMD(chr(1))
        __import__("time").sleep(.03)

    def home(self):
        """
        set the Cursor to HOME
        """
        self._lcdCMD(b"\x02")
        __import__("time").sleep(.05)

    def cursor(self, x=0, y=0):
        """
        the the Cursor to x,y
        0,0 = HOME
        """
        if type(x) == tuple:
            x, y = x
        if y == 0:
            pos = x + 0x80
        else:
            pos = x + 0xC0
        self._lcdCMD(pos)

    def write(self, txt, pos=False):
        """
        write txt to LCD at pos-ition
        txt: string with text
        pos: tuple with coordinates, or False
        """
        if pos:
            self.cursor(pos)
        for i in txt:
            self._lcdDAT(i)

    def charAt(self, char, pos=(0, 0)):
        """
        write character to the LCD at pos-ition
        char: character
        pos: tuple with coordinates
        """
        self.cursor(pos)
        self._lcdDAT(char)

    def saveChar(self, char, pxl):
        """
        define a custom-character
        char: integer (0-7) charactercode
        pxl: 2dimensional boolean list with pixels
        """
        char = char % 8
        data = b""
        for x in pxl:
            data += chr(int("".join([str(i) for i in x]), 2)).encode("ASCII")
        self._lcdCMD((char << 3) | 0x40)
        self._lcdDAT(data)

    def _lcdCMD(self, command):
        """write command bytes to lcd"""
        if type(command) == int:
            command = command.to_bytes(1, "big")
        elif type(command) == str:
            command = command.encode("ASCII")
        self._i2c.writeto(self._lcd, self._cmd + command)

    def _lcdDAT(self, data):
        """ write data bytes to lcd """
        if type(data) == int:
            data = data.to_bytes(1, "big")
        elif type(data) == str:
            data = data.encode("ASCII")
        self._i2c.writeto(self._lcd, self._dat + data)
