"""Module 08: measure the relative sound level of the PDM microphone."""

import array
import math
import time
import board
import audiobusio
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()


def calculate_rms(values):
    average = sum(values) / len(values)
    total = 0.0
    for sample in values:
        total += (sample - average) * (sample - average)
    return math.sqrt(total / len(values))


i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
microphone = audiobusio.PDMIn(
    board.GP3,
    board.GP2,
    sample_rate=16000,
    bit_depth=16,
)
samples = array.array("H", [0] * 100)

try:
    while True:
        microphone.record(samples, len(samples))
        magnitude = calculate_rms(samples)
        relative_db = 20 * math.log(magnitude) / math.log(10) if magnitude else 0
        show_module(oled, 8, "PDM Microphone", (
            "Clock GP3 / Data GP2",
            "Magnitude: {:.1f}".format(magnitude),
            "Relative dB: {:.1f}".format(relative_db),
        ))
        print("Magnitude: {:.1f}, relative dB: {:.1f}".format(
            magnitude, relative_db
        ))
        time.sleep(0.05)
finally:
    microphone.deinit()
    i2c.deinit()
