import numpy as np
import Apodization
import pandas as pd
import os
from scipy.interpolate import interp1d


def dft(interf, pos, start_freq, end_freq, samples):
    dpos=np.diff(pos)
    dpos=np.append(dpos,0)
    freq = np.linspace(start_freq, end_freq, samples)  # Creating frequency axis
    pos = pos.reshape(len(pos), 1)
    a = np.exp(-1j * 2 * np.pi * pos * freq)
    b = dpos * interf
    spect = b.dot(a)    # computes the dft

    return spect, freq

def movmean(A, n):
    ser = pd.Series(A)
    data_mean = ser.rolling(window=n, min_periods=1, center=True).mean()

    moved_averages = pd.DataFrame.to_numpy(data_mean)

    return moved_averages


def get_spectrum(interferogram, position_axis, start_wavelength, end_wavelength, samples, apodization_width):
    # Load spectral calibration file
    items = os.listdir(".")

    for names in items:
        if names.endswith("parameters_cal.txt"):
            filename = names

    ref = np.genfromtxt(filename, delimiter = '\t')
    wavelength = (ref[0,:])
    reciprocal = (ref[1,:])


    # Compute the frequency limits from the calibration file
    fn = interp1d(1 / wavelength, reciprocal, kind="linear")
    start_freq = fn(1 / end_wavelength)
    end_freq = fn(1 / start_wavelength)
    np.reshape(interferogram, len(interferogram))

    '''
    P_freq2wave, P_wave2freq = Spectral_calibration.spectral_calibration()
    start_freq = np.polyval(P_wave2freq, 1 / end_wavelength)
    end_freq = np.polyval(P_wave2freq, 1 / start_wavelength)
    '''



    array_mean_move = movmean(interferogram, int(len(interferogram) / 5))

    signal = Apodization.apodization(interferogram - array_mean_move, position_axis, apodization_width)
    signal_ph = Apodization.apodization(interferogram - array_mean_move, position_axis, apodization_width * 0.1)

    spect_mod, freq = dft(signal, position_axis, start_freq, end_freq, samples)
    spect_ph, freq = dft(signal_ph, position_axis, start_freq, end_freq, samples)

    spectrum = np.real(spect_mod * np.exp(-1j * np.angle(spect_ph)))

    # Compute the calibrated wavelength axis
    fn = interp1d(reciprocal, 1 / wavelength, kind="linear")
    wave = 1 / fn(freq)
    #wave = 1 / np.polyval(P_freq2wave, freq)

    return spectrum, wave, freq, signal
