# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Exercise: an LED control class on Raspberry Pi, tested with a mock GPIO
# Runs anywhere (Google Colab, a laptop, the Pi itself). On a real Raspberry Pi,
# delete the MockGPIO class and write:  import RPi.GPIO as GPIO

import time                         # time.sleep() for the blink timing


# ---- Mock RPi.GPIO: prints every call instead of driving real hardware
class MockGPIO:
    """Stand-in for the RPi.GPIO library, so the class can be tested without a Pi."""
    BCM = 'BCM'                     # numbering mode: Broadcom GPIO numbers (GPIO17)
    OUT = 'OUT'                     # pin direction: output
    HIGH = True                     # logic 1 → 3.3 V on the pin → LED on
    LOW = False                     # logic 0 → 0 V on the pin → LED off

    @staticmethod
    def setmode(mode):
        """Choose the pin numbering scheme (here BCM)."""
        print(f"GPIO mode set to {mode}")

    @staticmethod
    def setup(pin, mode):
        """Configure one pin as input or output."""
        print(f"GPIO pin {pin} set up as {mode}")

    @staticmethod
    def output(pin, state):
        """Drive an output pin HIGH or LOW."""
        print(f"GPIO pin {pin} set to {'HIGH' if state else 'LOW'}")

    @staticmethod
    def cleanup():
        """Release every pin the program used (back to safe inputs)."""
        print("GPIO cleanup")


GPIO = MockGPIO                     # on a real Pi: import RPi.GPIO as GPIO


# ---- The LED class: one object = one LED on one GPIO pin
class LED:
    """Control an LED connected (through a resistor) to one GPIO pin."""

    def __init__(self, pin: int) -> None:
        """Set the pin up as an output and start with the LED OFF."""
        self.pin = pin                          # remember which pin this LED uses
        GPIO.setmode(GPIO.BCM)                  # use BCM (GPIO) numbers, not header numbers
        GPIO.setup(self.pin, GPIO.OUT)          # the pin drives the LED → output
        self.state = GPIO.LOW                   # the object keeps the current state
        GPIO.output(self.pin, self.state)       # start OFF

    def __repr__(self) -> str:
        """Developer view, e.g. in a list or the interpreter: LED(pin=17, state=OFF)."""
        return f"LED(pin={self.pin}, state={'ON' if self.state == GPIO.HIGH else 'OFF'})"

    def __str__(self) -> str:
        """Readable view used by print(led)."""
        return f"LED on pin {self.pin} is {'ON' if self.state == GPIO.HIGH else 'OFF'}"

    # ---- Basic switching: update the stored state, then drive the pin
    def turn_on(self) -> None:
        """Switch the LED on (pin HIGH)."""
        self.state = GPIO.HIGH
        GPIO.output(self.pin, self.state)

    def turn_off(self) -> None:
        """Switch the LED off (pin LOW)."""
        self.state = GPIO.LOW
        GPIO.output(self.pin, self.state)

    def toggle(self) -> None:
        """Invert the state: ON becomes OFF and OFF becomes ON."""
        self.state = GPIO.LOW if self.state == GPIO.HIGH else GPIO.HIGH
        GPIO.output(self.pin, self.state)

    def blink(self, times: int = 1, on_time: float = 0.5, off_time: float = 0.5) -> None:
        """Blink `times` times: on for on_time seconds, then off for off_time seconds."""
        for _ in range(times):
            self.turn_on()
            time.sleep(on_time)
            self.turn_off()
            time.sleep(off_time)

    # ---- Pin validation: belongs to the class, needs no object → @staticmethod
    @staticmethod
    def check_pin_availability(pin: int) -> bool:
        """True if the number is in the accepted range (BCM GPIO2–27)."""
        return isinstance(pin, int) and 2 <= pin <= 27

    # ---- Safe factory: build an LED only for a valid pin → @classmethod
    @classmethod
    def create_led(cls, pin: int) -> 'LED':
        """Return a new LED, or raise ValueError if the pin is not available."""
        if cls.check_pin_availability(pin):
            return cls(pin)
        else:
            raise ValueError("GPIO pin is not available")

    def pattern(self, symbols: str) -> None:
        """Dot = short flash, dash = long flash; reject invalid symbols first."""
        if not symbols or any(c not in '.-' for c in symbols):
            raise ValueError('Use only dot and dash')
        for c in symbols:
            self.blink(1, 0.15 if c == '.' else 0.45, 0.15)

    def cleanup(self) -> None:
        """Release the GPIO pins when the program ends."""
        GPIO.cleanup()


# ---- Main script: LED on GPIO17, print it, blink 3 times, always clean up
if __name__ == "__main__":
    led = None                                  # defined before try, so finally can test it
    try:
        led_pin = 17                            # BCM GPIO17 = physical header pin 11
        led = LED.create_led(led_pin)           # validated construction
        print(led)                              # __str__ → "LED on pin 17 is OFF"
        led.blink(3)                            # 3 × (0.5 s ON + 0.5 s OFF)
    finally:
        if led is not None:                     # cleanup only if the LED was created
            led.cleanup()                       # runs even if an error happened above
