"""Module 05: calculate illuminance and colour temperature with APDS9960."""

import time
from adafruit_apds9960.apds9960 import APDS9960
from adafruit_apds9960 import colorutility
import board
import busio
import adafruit_ssd1306


def show_module(oled, number, title, lines):
    """Draw this lesson's OLED screen without an external helper module."""
    oled.fill(0)
    oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
    for index, line in enumerate(lines[:4]):
        oled.text(str(line)[:21], 0, 16 + index * 11, 1)
    oled.show()


i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
sensor = APDS9960(i2c)
sensor.enable_color = True

try:
    while True:
        while not sensor.color_data_ready:
            time.sleep(0.005)
        red, green, blue, clear = sensor.color_data
        lux = colorutility.calculate_lux(red, green, blue)
        try:
            colour_temp = colorutility.calculate_color_temperature(red, green, blue)
            temperature_text = '{:.2f} K'.format(colour_temp)
        except ZeroDivisionError:
            # Dark or degenerate RGB readings cannot define a colour temperature.
            temperature_text = 'unavailable'
        show_module(oled, 5, "APDS9960 Light", (
            "Lux: {:.2f}".format(lux),
            "Temp: " + temperature_text,
            "Clear: {}".format(clear),
        ))
        print("Lux: {:.2f}, colour temperature: {}".format(
            lux, temperature_text
        ))
        time.sleep(1)
finally:
    sensor.enable_color = False
    i2c.deinit()
