from src.hardware.constraints import HardwareConstraints


class Synchronizer:
    def __init__(self, hw: HardwareConstraints):
        self.hw = hw

    def process(self, sync_sequence):
        """
        Повторяет логику synchronization(...) из test1_full/srv_interp.py
        и возвращает все массивы, нужные для экспорта XML и PicoScope.
        """
        synchro_block_timer = self.hw.MIN_BLOCK_DURATION
        tr_delay = self.hw.TR_DELAY
        rf_delay = self.hw.RF_DELAY
        start_delay = max(self.hw.START_DELAY, self.hw.RF_DELAY)

        min_block_time = 800e-9

        if tr_delay < synchro_block_timer:
            tr_delay = synchro_block_timer
        if rf_delay < synchro_block_timer:
            rf_delay = synchro_block_timer

        number_of_blocks = len(sync_sequence.block_events)
        gate_adc = [0]
        gate_rf = [0]
        gate_tr_switch = [1]
        blocks_duration = [start_delay]

        added_blocks = 0
        for block_counter in range(number_of_blocks):
            is_not_adc_block = True

            if sync_sequence.block_events[block_counter + 1][5]:
                is_not_adc_block = False

                gate_adc.append(0)
                gate_rf.append(gate_rf[-1])
                blocks_duration[-1] -= tr_delay
                blocks_duration.append(tr_delay)
                gate_tr_switch.append(0)
                added_blocks += 1

                gate_adc.append(1)
                gate_tr_switch.append(0)
            else:
                gate_tr_switch.append(1)
                gate_adc.append(0)

            if sync_sequence.block_events[block_counter + 1][1] and is_not_adc_block:
                gate_rf.append(1)
                gate_adc.append(gate_adc[-1])
                blocks_duration[-1] -= rf_delay
                blocks_duration.append(rf_delay)
                gate_tr_switch.append(gate_tr_switch[-1])
                added_blocks += 1

                gate_rf.append(1)
            else:
                gate_rf.append(0)

            current_block_dur = sync_sequence.block_durations[block_counter + 1]
            blocks_duration.append(current_block_dur)

        number_of_blocks += added_blocks

        return {
            "number_of_blocks": number_of_blocks,
            "gate_adc": gate_adc,
            "gate_rf": gate_rf,
            "gate_tr_switch": gate_tr_switch,
            "blocks_duration": blocks_duration,
            "synchro_block_timer": synchro_block_timer,
            "min_block_time": min_block_time,
        }
