'''
Created on 29 août 2022

@author: denis
'''
import logging
import threading
from RPLCD.i2c import CharLCD

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

#lcd = CharLCD(settings.LCD_EXPANDER, settings.LCD_ADDR, port=settings.LCD_PORT)


class LCD():
    def __init__(self, lcd, timeout=None):
        self.lcd = lcd
        self.waiter = threading.Event()
        self.cols = 16
        self.timeout = timeout
        self.screen_enabled = True

    @property
    def screen_enabled(self):
        return self._enabled

    @screen_enabled.setter
    def screen_enabled(self, v):
        self.lcd.backlight_enabled = v
        self._enabled = v


    def create_char(self, pos, cc):
        self.lcd.create_char(pos, cc)


    # LCD display
    def _display(self, event, msg, timeout):
        self.screen_enabled = True
        self.lcd.clear()
        self.lcd.write_string(msg)
        event.wait(timeout)
        self.screen_enabled = False


    def write_msg(self, msg, timeout=5):
        if not self.waiter.is_set():
            self.waiter.set()
        self.waiter = threading.Event()
        threading.Thread(target=self._display, args=(self.waiter, msg, timeout, )).start()


    def _screen_enable(self, event, timeout):
        self.screen_enabled = True
        event.wait(timeout)
        self.screen_enabled = False


    def screen_disable(self):
        if not self.waiter.is_set():
            self.waiter.set()
        self.screen_enabled = False


    def screen_enable(self):
        if self.timeout is not None:
            if not self.waiter.is_set():
                self.waiter.set()
            self.waiter = threading.Event()
            threading.Thread(target=self._screen_enable, args=(self.waiter, self.timeout, )).start()
        else:
            self.screen_enabled = True


    def display(self, msg, pos=(0, 0), align=None, clear=True):
        self.screen_enable()

        if clear:
            self.lcd.clear()
        self.lcd.cursor_pos = pos
        if align=='left':
            self.lcd.write_string(msg.ljust(self.cols))
        elif align=='right':
            self.lcd.write_string(msg.rjust(self.cols))
        else:
            self.lcd.write_string(msg)

