import plot_lib
import read_file
import editing_data
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as signal
import os

matplotlib.use('Qt5Agg')

def plot1():
    volt_in, volt_out = read_file.read_xy_file("prak2/test.txt")

    y = [volt_in, volt_out]
    x = volt_in

    labels = ["Ideale Kennlinie", "Reale Kennlinie"]

    plot_lib.plot_shared_xy(
        x=x,
        y_list=y,
        xlabel="Input Voltage (V)",
        ylabel="Output Voltage (V)",
        title="Kennlinie des Tiefpassfilters",
        show_points=True,
        save_path="prak2/kennlinie_tiefpass.svg",
        labels=labels
    )

    diff = plot_lib.plot_difference(
        x=x,
        y1=y[0],
        y2=y[1],
        return_sum=True,
        xlabel="Input Voltage (V)",
        ylabel="Output Voltage (V)",
        title="Differenz der idealen und realen Kennlinie des Tiefpassfilters",
        show_points=True,
        save_path="prak2/kennlinie_tiefpass_diff.svg"
    )

    print(diff)

def plot2():
    data_1k, indecies = read_file.read_data_with_indices("prak2/333_output1k.txt")
    data_3k, _ = read_file.read_data_with_indices("prak2/333_output3k.txt")
    data_5k, _ = read_file.read_data_with_indices("prak2/333_output5k.txt")
    data = [data_1k, data_3k, data_5k]
    labels = [r"$1\,\mathrm{k\Omega}$", r"$3\,\mathrm{k\Omega}$", r"$5\,\mathrm{k\Omega}$"]
    colors = ["red", "green", "blue"]
    indecies = indecies*1000
    ys = []
    xs = []

    length = 169

    figsize = (10, 6)
    plt.figure(figsize=figsize)

    for i in range(len(data)):
        idxs = editing_data.detect_step_segments(data[i], diff_threshold=0.2, min_length=50)
        # print(i, idxs)
        y = data[i][idxs[0][0]:idxs[0][0]+length]
        x = np.arange(0, len(y)) / 48000 *1000000  # Zeit in mycrosekunden
        plt.plot(x, y, label=labels[i] + " (Messung)", color=colors[i], linestyle='--', marker='x', markersize=8)
        ys.append(y)
        xs.append(x)
    
    C = 100e-9  
    R = [1e3, 3e3, 5e3]

    t = np.linspace(0, 0.0035, 1000)
    
    for i in range(len(R)):
        Rs = R[i]
        label = labels[i]
        num = [5]           
        den = [Rs*C, 1]
        system = signal.TransferFunction(num, den)
        t_out, y = signal.step(system, T=t)
        t_out = t_out * 1000 * 1000
        plt.plot(t_out,  y, label=label + " (Ideal)", color=colors[i])

    plt.xlim(0, 1.5*1000)
    plt.ylim(0, 5.5)
    plt.xlabel(r"Zeit ($\mu s$)")
    # plt.xlabel(r"Zeit (ms)")
    plt.ylabel("Voltage (V)")
    plt.title("Sprungantwort des Tiefpassfilters")
    plt.grid()
    plt.legend()
    plt.tight_layout()

    save_path=f"prak2/tiefpass_mult_r.svg"
    plt.savefig(save_path, format="svg")
    plt.show()

if __name__ == "__main__":
    # plot1()
    plot2()