import sys
import serial
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QMainWindow
from mainwindow import Ui_MainWindow

# communication function
class SerialThread(QThread):
    dataReady = pyqtSignal(bytes)
    SERIALPORT = '/dev/cu.usbmodem1D11431' #change value for respective port
    BAUDRATE = 115200

    def __init__(self, serial_port=SERIALPORT, baud_rate=BAUDRATE):
        super(SerialThread, self).__init__()
        self.uart = serial.Serial(serial_port, baud_rate, timeout=1)

    def run(self):
        while True:
            self.buffer = self.uart.readline()
            if len(self.buffer) > 0:
                self.dataReady.emit(self.buffer)
            else:
                self.buffer = b''

class MaterialTester(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MaterialTester, self).__init__()
        self.setupUi(self)

        self.uart = SerialThread()
        self.uart.dataReady.connect(self.getFreq)
        self.uart.start()

        self.materialName.setText("Acrylic")
        self.materialLength.setText("302")
        self.materialWidth.setText("128")
        self.materialHeight.setText("4")  # thickness
        self.materialMass.setText("Mass")
        self.materialFrequency.setText("Read Freq")


    def getFreq(self, fft_list):

        #print(fft_list)
        fft_str = str(fft_list, 'utf-8').split(',')  # get a list of fft values
        del fft_str[-1]  # discard last value '\r\n'
        fft_int = list(map(int, fft_str))  # convert the string list to integer list
        fft_max = max(fft_int)
        fft_max_index = fft_int.index(fft_max)
        print(fft_int)
        print(fft_max)
        print(fft_max_index)


    def calculateMaterial(self):
        self.materialElasticity.setText("Calculation")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MaterialTester()
    main_window.show()
    sys.exit(app.exec_())