import numpy as np


class RFExporter:
    """
    Экспорт RF в формате test1_full/srv_interp.py
    """

    @staticmethod
    def _radio_ampl_convertation(rf_ampl, t_rf, rf_raster_local):
        out_rf_list = []
        rf_ampl_raster = 127
        rf_ampl_maximum = np.abs(max(rf_ampl)) if len(rf_ampl) else 0
        if rf_ampl_maximum == 0:
            return out_rf_list

        proportional_cf_rf = rf_ampl_raster / rf_ampl_maximum
        num_zeroes = 0
        for rf_iter in range(len(rf_ampl) - 1):
            if abs(t_rf[rf_iter] - t_rf[rf_iter + 1]) > 2 * rf_raster_local:
                num_zeroes += int(np.abs((t_rf[rf_iter] - t_rf[rf_iter + 1]) / rf_raster_local))
            else:
                out_rf_list += [0] * num_zeroes
                num_zeroes = 0
                out_rf_list.append(round(rf_ampl[rf_iter].real * proportional_cf_rf))
                out_rf_list.append(round(rf_ampl[rf_iter].imag * proportional_cf_rf))
        return out_rf_list

    def export(self, waveforms: dict, params: dict, output_dir: str):
        rf_raster_local = params["rf_raster_time"]

        if rf_raster_local == 5e-7:
            empty_block_time_delay = 17.7e-6
        elif rf_raster_local == 2.5e-7:
            empty_block_time_delay = 3.6e-6
        elif rf_raster_local == 5e-8:
            empty_block_time_delay = 1.77e-6
        else:
            empty_block_time_delay = 0

        rf_out = [0] * int(2 * (empty_block_time_delay // rf_raster_local))
        rf_out += self._radio_ampl_convertation(
            waveforms["rf"],
            waveforms["t_rf"],
            rf_raster_local,
        )

        scale_rf = params.get("scale_rf", 1.0)
        rf_out = [round(x * scale_rf) for x in rf_out]

        file_path = f"{output_dir}/rf_{rf_raster_local}_raster.bin"
        with open(file_path, "wb") as file_rf:
            for byte in rf_out:
                file_rf.write(int(byte).to_bytes(1, byteorder="big", signed=True))

        np.savetxt(f"{output_dir}/rf_time.txt", np.transpose(waveforms["t_rf"]))
        np.savetxt(f"{output_dir}/rf_ampl.txt", np.transpose(waveforms["rf"]))
