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

if __name__ == '__main__':
    with open('signals.csv', 'r') as f:

        for line in f:
            hex = line.split('\t')[3].replace('\n', '')[3:]
            signal = np.frombuffer(bytes.fromhex(hex), dtype=np.int16)
            fig = plt.figure('signal')

            plt.xlabel('t [ms]')
            plt.ylabel('ADC [-]')
            plt.grid()

            orezat = [False, False, False, False]
            signal_filtr = []
            contribution = 200

            for i in range(len(signal) - 4):
                if (signal[i + 4] - signal[i + 3]) > contribution:
                    orezat[0] = True
                if (signal[i + 3] - signal[i + 2]) > contribution:
                    orezat[1] = True
                if (signal[i + 2] - signal[i + 1]) > contribution:
                    orezat[2] = True
                if (signal[i + 1] - signal[i]) > contribution:
                    orezat[3] = True
                if orezat[0] == True and orezat[1] == True and orezat[2] == True and orezat[3] == True:
                    bod = signal[i]
                    break

            for i in range(len(signal)):
                if signal[i] - bod > 0:
                    signal_filtr.append(signal[i] - bod)
                else:
                    signal_filtr.append(0)


            plt.plot(signal, label="původní signal")
            plt.plot(signal_filtr, label="signál po prahování")
            plt.legend()

            # prevod na np array
            signal_filtr = np.array(signal_filtr)

            # vyhledani peaku
            peaks, _ = find_peaks(signal_filtr, height=3000, prominence=2000)

            # zobrazeni peaku
            plt.plot(peaks, signal_filtr[peaks], "xr", label='vrcholy')
            plt.legend()
            save_signal = np.array2string(signal_filtr, max_line_width=1000, separator=',')

            # ukladani do souboru
            with open('detekce.csv', 'a+') as det:
                 header = ['Detekce', 'Signal']
                 writer = csv.DictWriter(det, fieldnames=header)
                 writer.writeheader()

                 if peaks.size == 2:
                    print("dvojmontaz")
                    writer.writerow({'Detekce': 'Dvojmontaz', 'Signal': signal})

                 elif peaks.size == 1:
                     print('jednomontaz')
                     writer.writerow({'Detekce': 'Jednoducha_montaz', 'Signal': signal})

                 else:
                     print('šum')

            plt.show()
