from migen import *
from migen.genlib.cdc import PulseSynchronizer


class Sampler(Module):
    def __init__(self, adc_pins: Record):
        # Hook up ADC REFCLK to sample_clock
        self.comb += adc_pins.refclk.eq(ClockDomain("sample_clock").clk)

        # We can synchronize to the sampler clock, whenever it goes high we can
        # strobe a single valid signal
        synchronizer = PulseSynchronizer("sample_clock", "sys")
        self.submodules += synchronizer

        self.valid = Signal()
        self.data = Signal(10)

        self.comb += [
            synchronizer.i.eq(ClockDomain("sample_clock").clk),
            self.valid.eq(synchronizer.o),
        ]
        self.sync += self.data.eq(adc_pins.data)

        # Set config pins to constant values
        self.comb += adc_pins.oen_b.eq(0)       # Data pins enable
        self.comb += adc_pins.standby.eq(0)     # Sampling standby
        self.comb += adc_pins.dfs.eq(0)         # DFS (raw or two's complement)
        # The only remaining pin, OTR, is an out of range status indicator
