import numpy as np


class GradientExporter:
    """
    Экспорт градиентных сигналов в формате test1_full/srv_interp.py
    """

    @staticmethod
    def _duplicates_delete(loc_list):
        new_list = [[0] * 2]
        for i in range(len(loc_list)):
            if loc_list[i][0] not in np.transpose(new_list)[0]:
                new_list.append(loc_list[i])
        return new_list

    @staticmethod
    def _gradient_time_convertation(params: dict, time_sample):
        g_raster_time = params["grad_raster_time"]
        return time_sample / g_raster_time

    @staticmethod
    def _gradient_ampl_convertation(params: dict, gradient_herz):
        amplitude_max = params["G_amp_max"]
        amplitude_raster = 32767
        step_hz_m = amplitude_max / amplitude_raster
        return gradient_herz / step_hz_m * 1000

    def export(self, waveforms: dict, params: dict, path: str) -> None:
        loc_t_gx = self._gradient_time_convertation(params, waveforms["t_gx"])
        loc_t_gy = self._gradient_time_convertation(params, waveforms["t_gy"])
        loc_t_gz = self._gradient_time_convertation(params, waveforms["t_gz"])

        loc_gx = self._gradient_ampl_convertation(params, waveforms["gx"])
        loc_gy = self._gradient_ampl_convertation(params, waveforms["gy"])
        loc_gz = self._gradient_ampl_convertation(params, waveforms["gz"])

        gx_out = self._duplicates_delete(np.transpose([loc_t_gx, loc_gx]))
        gy_out = self._duplicates_delete(np.transpose([loc_t_gy, loc_gy]))
        gz_out = self._duplicates_delete(np.transpose([loc_t_gz, loc_gz]))

        np.savetxt(f"{path}/gx.txt", gx_out, fmt="%10.0f")
        np.savetxt(f"{path}/gy.txt", gy_out, fmt="%10.0f")
        np.savetxt(f"{path}/gz.txt", gz_out, fmt="%10.0f")
