import os
import csv
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import find_peaks

def plot_spectrogram_with_peak_spectrum(column1_data, column2_data, fs):
    """
    Plot a spectrogram and its spectrum with highlighted peak values.

    Parameters:
        column1_data (list): List of data for column 1.
        column2_data (list): List of data for column 2.
        fs (float): Sampling frequency (Hz).

    Returns:
        None
    """
    # Combine the two columns of data into a single array
    data = np.array(column2_data)  # You can use column1_data or column2_data depending on which column you want to analyze
    
    # Perform FFT
    n = len(data)
    freqs = np.fft.fftfreq(n, 1/fs)

    fft_values = np.fft.rfft(data)

    #neu
    fft_val = 2 / len(data) * np.abs(fft_values)
    fft_values_db = 20 * np.log(fft_val)
    fft_mag = fft_values_db

    #fft_mag = np.abs(fft_values)
    # Find peaks in the positive frequencies of the spectrum
    positive_freqs_mask = freqs >= 0
    positive_freqs = freqs[positive_freqs_mask]
    #fft_mag_positive = fft_mag[positive_freqs_mask]

    #peaks, _ = find_peaks(fft_mag_positive, height=800000)

    # Plot spectrogram
    plt.figure(figsize=(12, 6))
    
    plt.subplot(1, 2, 1)
    plt.specgram(data, Fs=fs, cmap='viridis')
    plt.xlabel('Zeit [s]')
    plt.ylabel('Frequenz [Hz]')
    plt.title('Spectrogram')
    plt.colorbar(label='Signalstärke [dB]')
    
    # Plot spectrum with highlighted peaks
    plt.subplot(1, 2, 2)
    plt.plot(freqs[:n//2], fft_mag[:n//2])  # Plot only the positive frequencies
    plt.xlabel('Frequenz (Hz)')
    plt.ylabel('Amplitude')
    plt.title('Frequenzspektrum')
    #plt.plot(freqs[peaks][:n//2], fft_mag[peaks][:n//2], 'ro', markersize=3)  # Highlight peaks
    plt.legend(['Spectrum'])
    
    # Print frequencies of peaks
    #print("Frequencies of peaks:")
    #for peak_index in peaks:
    #    peak_freq = positive_freqs[peak_index]
    #    print(f"{peak_freq:.2f} Hz")

    plt.tight_layout()
    if save: plt.savefig(f"analysing/auswertung/V1_Freq_{signal_rate}HzSinus{sample_rate}HzSampleRate.png")
    plt.show()

# Example usage:
# Replace column1_data and column2_data with your actual data, and fs with the sampling frequency
# For example:
# plot_spectrogram_with_spectrum(column1_data, column2_data, fs)



time = []
data = []
sample_rate = 8000
signal_rate = 3950
save = True
# Open the CSV file for reading
with open(f'analysing/V1_{sample_rate}SR_{signal_rate}Hz.txt', 'r') as file:
    # Create a CSV reader object
    csv_reader = csv.reader(file)
    # Skip the header
    next(csv_reader)
    
    # Iterate over each row in the CSV file
    for row in csv_reader:
        # Assuming each row has two columns
        val = float(row[0])
        data.append(val)
    
    #print(data)

PERIOD_DURATION = 1/sample_rate
for data_points in range(len(data)):
    time.append(data_points * PERIOD_DURATION)
#print(time)

# Plotting the data as a line plot
plt.figure(figsize=(8, 6))
plt.plot(time, data, color='blue', linestyle='-', marker="*")
plt.title(f'{signal_rate} Hz Sinus mit {sample_rate} Hz abgetastet')
plt.xlabel('Zeit [s]')
plt.ylabel('Spannung [V]')
plt.grid(True)
if save: plt.savefig(f"analysing/auswertung/V1_{signal_rate}HzSinus{sample_rate}HzSampleRate.png")
plt.show()

plot_spectrogram_with_peak_spectrum(time, data, sample_rate)