from pathlib import Path
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
from func.Filters.Preprocessing import Butterworth_for_ECG_PreProcess, Butterworth_for_BCG_PreProcess

# # 原始
# psg_dir = Path(r"E:\code\DataCombine2023\ZD5Y2\PSG_Text\10787")
# org_bcg_dir = Path(r"E:\code\DataCombine2023\ZD5Y2\OrgBCG_Text\10787")
# tho_file_path = psg_dir / "Effort Tho_Raw_100.txt"
# abd_file_path = psg_dir / "Effort Abd_Raw_100.txt"
# tho_fs = 100
# abd_fs = 100
# orgbcg_file_path = org_bcg_dir / "OrgBCG_Raw_500.txt"
# orgbcg_fs = 500

# 对齐后
psg_dir = Path(r"E:\code\DataCombine2023\ZD5Y2\PSG_Aligned\10787")
org_bcg_dir = Path(r"E:\code\DataCombine2023\ZD5Y2\OrgBCG_Aligned\10787")
tho_file_path = psg_dir / "Effort Tho_Sync_100.txt"
abd_file_path = psg_dir / "Effort Abd_Sync_100.txt"
tho_fs = 100
abd_fs = 100
orgbcg_file_path = org_bcg_dir / "OrgBCG_Sync_1000.txt"
orgbcg_fs = 1000


tho_raw = pd.read_csv(tho_file_path, header=None).to_numpy().reshape(-1)
abd_raw = pd.read_csv(abd_file_path, header=None).to_numpy().reshape(-1)
orgbcg_raw = pd.read_csv(orgbcg_file_path, header=None).to_numpy().reshape(-1)

tho_filtered = Butterworth_for_ECG_PreProcess(tho_raw, tho_fs, type="bandpass", low_cut=0.01, high_cut=15.0, order=4)
abd_filtered = Butterworth_for_ECG_PreProcess(abd_raw, abd_fs, type="bandpass", low_cut=0.01, high_cut=15.0, order=4)
orgbcg_filtered = Butterworth_for_BCG_PreProcess(orgbcg_raw, orgbcg_fs, type="bandpass", low_cut=0.01, high_cut=0.7, order=4)


# 降采样
orgbcg_filtered = orgbcg_filtered[::orgbcg_fs//10]  # 从500Hz降采样到10Hz
tho_filtered = tho_filtered[::tho_fs//10]  # 从100Hz降采样到10Hz
abd_filtered = abd_filtered[::abd_fs//10]  # 从100Hz降采样到10Hz

plt.figure(figsize=(12, 8))
psg_x = np.linspace(0, len(tho_filtered) / 10, len(tho_filtered))
orgbcg_x = np.linspace(0, len(orgbcg_filtered) / 10, len(orgbcg_filtered))

plt.subplot(3, 1, 1)
plt.plot(psg_x, tho_filtered, label='Thoracic Effort', color='blue')
plt.title('Thoracic Effort Signal (Filtered)')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.grid()
plt.legend()

plt.subplot(3, 1, 2)
plt.plot(psg_x, abd_filtered, label='Abdominal Effort', color='green')
plt.title('Abdominal Effort Signal (Filtered)')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.grid()
plt.legend()

plt.subplot(3, 1, 3)
plt.plot(orgbcg_x, orgbcg_filtered, label='Original BCG', color='red')
plt.title('Original BCG Signal (Filtered)')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.grid()
plt.legend()
plt.tight_layout()
plt.show()

