# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Example 2: a traffic light built from three LED objects (composition)
# 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 (simulation assumption: 1–40)."""
        return 1 <= pin <= 40

    # ---- 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 cleanup(self) -> None:
        """Release the GPIO pins when the program ends."""
        GPIO.cleanup()



# ---- TrafficLight: one object that owns three LED objects
class TrafficLight:
    """Red, yellow and green LEDs controlled as one traffic light."""
    ORDER = ('green', 'yellow', 'red')          # the order of one full cycle

    def __init__(self, red_pin: int = 17, yellow_pin: int = 27, green_pin: int = 22) -> None:
        """Create the three LEDs (each one validated by LED.create_led)."""
        self.leds = {'red': LED.create_led(red_pin),       # composition: a TrafficLight
                     'yellow': LED.create_led(yellow_pin), # HAS three LEDs; it is not
                     'green': LED.create_led(green_pin)}   # itself an LED
        self.current = None                                 # no colour shown yet

    def __repr__(self) -> str:
        """Developer view: which pin each colour uses."""
        return (f"TrafficLight(red={self.leds['red'].pin}, "
                f"yellow={self.leds['yellow'].pin}, green={self.leds['green'].pin})")

    def __str__(self) -> str:
        """Readable view used by print()."""
        return f"Traffic light shows {self.current.upper() if self.current else 'nothing'}"

    # ---- Show exactly one colour: switch the old one off, the new one on
    def show(self, colour: str) -> None:
        """Light only `colour`; raise ValueError for an unknown colour."""
        if colour not in self.leds:
            raise ValueError(f"unknown colour: {colour}")
        if self.current:                                    # something is lit
            self.leds[self.current].turn_off()
        self.leds[colour].turn_on()
        self.current = colour

    def cycle(self, times: int = 1, green: float = 2.0, yellow: float = 0.5, red: float = 2.0) -> None:
        """Run green → yellow → red `times` times, holding each colour for its duration."""
        hold = {'green': green, 'yellow': yellow, 'red': red}
        for _ in range(times):
            for colour in self.ORDER:
                self.show(colour)
                print(self)                                 # __str__
                time.sleep(hold[colour])

    def cleanup(self) -> None:
        """Everything off, then release the pins."""
        for led in self.leds.values():
            led.turn_off()
        GPIO.cleanup()


# ---- Main script: one full cycle with short (demo) timings, always clean up
light = None
try:
    light = TrafficLight()                  # red GPIO17, yellow GPIO27, green GPIO22
    print(repr(light))                      # __repr__
    light.cycle(times=1, green=1.0, yellow=0.5, red=1.0)
finally:
    if light is not None:
        light.cleanup()
