"""Module 17: rotate a 28BYJ-48 stepper through a ULN2003 driver."""

import time
import board
import digitalio
import busio
import adafruit_ssd1306
from adafruit_motor import stepper


class ValueDisplay:
    """Send only the two changing OLED rows, in short idle-time transactions."""

    def __init__(self, oled, i2c):
        self.oled = oled
        self.i2c = i2c
        self.buffer = getattr(oled, 'buffer', None)
        self.partial = (self.buffer is not None and len(self.buffer) == 1025
                        and self.buffer[0] == 0x40
                        and not getattr(oled, 'page_addressing', False))
        self.pages = bytearray(256)
        self.command = bytearray((0x00, 0x21, 0, 15, 0x22, 3, 3))
        self.packet = bytearray(17)
        self.packet[0] = 0x40
        self.cancel()

    def cancel(self):
        self.busy = False

    def queue(self, step, angle, total_steps=4096):
        self.labels = ('Step: {}/{}'.format(step, total_steps), 'Est angle: {:.1f} deg'.format(angle))
        self.row = 0
        self.offset = 0
        self.busy = True

    def service(self):
        if not self.busy:
            return
        if self.row < 2:
            # Render one row per idle slot; do not redraw the full screen.
            y = 24 if self.row == 0 else 40
            self.oled.fill_rect(0, y, 128, 8, 0)
            self.oled.text(self.labels[self.row], 0, y, 1)
            if self.partial:
                start = 1 + (y // 8) * 128
                self.pages[self.row * 128:(self.row + 1) * 128] = self.buffer[start:start + 128]
            self.row += 1
            return
        if not self.partial:
            # The desktop simulator represents OLED commands rather than a framebuffer.
            if hasattr(self.oled, 'commands'):
                self.oled.show()
            # An unrecognised hardware framebuffer gets endpoint updates only.
            self.busy = False
            return
        if not self.i2c.try_lock():
            return
        try:
            page = 3 if self.offset < 128 else 5
            column = self.offset % 128
            self.command[2] = column
            self.command[3] = column + 15
            self.command[5] = page
            self.command[6] = page
            self.packet[1:] = self.pages[self.offset:self.offset + 16]
            self.i2c.writeto(0x3C, self.command)
            self.i2c.writeto(0x3C, self.packet)
        finally:
            self.i2c.unlock()
        self.offset += 16
        if self.offset == 256:
            self.busy = False


PINS = (board.GP26, board.GP27, board.GP8, board.GP7)
STEPS_PER_ROTATION = 4096
STEP_DELAY = 0.004  # Slower target: 250 half-steps/second before processing overhead.
START_DELAY = 0.006  # Start and finish each movement more gently.
RAMP_STEPS = 256
PAUSE_SECONDS = 2.0
DISPLAY_INTERVAL = 1.0
OLED_IDLE_BUDGET = 0.003  # Service the OLED only with at least 3 ms until the next step.

i2c = busio.I2C(board.GP5, board.GP4, frequency=400000)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
value_display = ValueDisplay(oled, i2c)
outputs = []
for pin_name in PINS:
    output = digitalio.DigitalInOut(pin_name)
    output.switch_to_output(value=False)
    outputs.append(output)

# Adafruit expects the driver inputs in IN1, IN3, IN2, IN4 order.
stepper_motor = stepper.StepperMotor(
    outputs[0], outputs[2], outputs[1], outputs[3], microsteps=None
)
direction = 1
current_step = 0
position_steps = 0
next_step = time.monotonic()
pause_until = 0


def display_angle():
    # Match the kit's printed scale: angles increase counter-clockwise.
    return (-position_steps * 360 / STEPS_PER_ROTATION) % 360


def update_display(status):
    # Full transfers happen only before motion starts or after it has stopped.
    value_display.cancel()
    oled.fill(0)
    oled.text('(17) Stepper Motor', 0, 0, 1)
    oled.text('Clockwise' if direction > 0 else 'Counter-clockwise', 0, 12, 1)
    oled.text('Step: {}/{}'.format(current_step, STEPS_PER_ROTATION), 0, 24, 1)
    oled.text('Est angle: {:.1f} deg'.format(display_angle()), 0, 40, 1)
    oled.text(status, 0, 56, 1)
    oled.show()


update_display("Running")
next_step = time.monotonic()
next_display = next_step + DISPLAY_INTERVAL
print("Direction: Clockwise")

try:
    while True:
        now = time.monotonic()
        if pause_until:
            if now < pause_until:
                time.sleep(0.001)
                continue
            pause_until = 0
            direction *= -1
            current_step = 0
            next_step = now
            label = "Clockwise" if direction > 0 else "Counter-clockwise"
            update_display("Running")
            next_step = time.monotonic()
            next_display = next_step + DISPLAY_INTERVAL
            print("Direction:", label)

        if now < next_step:
            if next_step - now >= OLED_IDLE_BUDGET:
                if now >= next_display and not value_display.busy:
                    value_display.queue(current_step, display_angle(),
                                        STEPS_PER_ROTATION)
                    next_display = now + DISPLAY_INTERVAL
                if value_display.busy:
                    value_display.service()
                else:
                    time.sleep(0.0001)
            else:
                time.sleep(0.0001)
            continue

        # BACKWARD follows the original increasing IN1–IN4 coil sequence.
        stepper_motor.onestep(
            direction=stepper.BACKWARD if direction > 0 else stepper.FORWARD,
            style=stepper.INTERLEAVE,
        )
        current_step += 1
        position_steps += direction
        ramp_progress = min(current_step, STEPS_PER_ROTATION - current_step, RAMP_STEPS)
        step_delay = START_DELAY - (START_DELAY - STEP_DELAY) * ramp_progress / RAMP_STEPS
        next_step = time.monotonic() + step_delay

        if current_step == STEPS_PER_ROTATION:
            stepper_motor.release()
            update_display("Paused")
            pause_until = time.monotonic() + PAUSE_SECONDS
finally:
    stepper_motor.release()
    for output in outputs:
        output.deinit()
    i2c.deinit()
