from amaranth import *
from amaranth_soc.wishbone import *
from amaranth_soc.memory import *


class LEDPeripheral(Elaboratable, Interface):
    def __init__(self, led_signal):
        Interface.__init__(self, addr_width=1, data_width=32)
        memory_map = MemoryMap(addr_width=1, data_width=32)
        #memory_map.add_resource("my_led", name="led_peripheral", size=1)
        self.memory_map = memory_map

        self.led = led_signal

    def elaborate(self, platform):
        m = Module()

        storage = Signal(1)

        # Always update read values (both wishbone and the LED outpu)
        m.d.comb += [
            self.dat_r[0].eq(storage),
            self.led.eq(storage),
        ]

        m.d.sync += self.ack.eq(0) # default to no ack
        with m.If(self.cyc & self.stb):
            # single cycle ack when CYC and STB are asserted
            m.d.sync += self.ack.eq(1)

            # Write to our storage register if the value has changed
            with m.If(self.we):
                m.d.sync += storage.eq(self.dat_w[0])

        return m
