# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'resource/terminal.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from ui_main_window import Ui_MainWindow
from settings_window import SettingsWindow
from work_thread_class import WorkThread
from PyQt5.QtCore import (Qt, QObject, QThread, pyqtSignal, QRect, QTimer)
from PyQt5.Qt import *
import sys
import glob
import random

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)  
        self.setObjectName("Terminal 1.1") 
        self.setMinimumSize(550, 250)
        self.richEdit.setReadOnly(True)
        self.btn_connect.move(self.width()- self.btn_connect.width() - 10, 60) 
        #self.btn_connect.setStyleSheet("")     
        self.btn_disconnect.move(self.width() - self.btn_disconnect.width() - 10, self.btn_disconnect.height() + 60 + 10) 
        self.btn_file_save.move(self.width() - self.btn_file_save.width() - 10, self.height() - self.btn_file_save.height() - 15)                                            
        # Если опустить ниже появится ошибка
        # костыль для второго окна UPD: уже нет, так как некторые настройки находятся в главном окне
        self.thread = WorkThread()
        self.comboBox_num_port.addItems(self.thread.serial_ports())
        self.comboBox_num_port.setEnabled(False)
        self.add_function()
        self.add_event()
        self.widget = SettingsWindow(self)
        baudrates = ['1200','2400', '4800', '9600', '19200', '38400', '57600', '115200']
        self.comboBox_baudrate.addItems(baudrates);
        self.comboBox_baudrate.setCurrentText('9600')
        self.widget.comboBox_baudrate.addItems(baudrates);
        self.widget.comboBox_baudrate.setCurrentText('9600')

        self.statusbar.setStyleSheet("border :3px solid black;")
        self.label_1 = QLabel(f'{self.thread.get_count_msg()}')
        self.statusbar.addPermanentWidget(self.label_1)     

    def add_event(self):
        self.resizeEvent = self.resize_event 

    def resize_event(self, event):
        self.btn_connect.move(self.width() - self.btn_connect.width() - 10, 60)
        self.btn_disconnect.move(self.width() - self.btn_disconnect.width() - 10, self.btn_disconnect.height() + 60 + 10)
        self.btn_file_save.move(self.width() - self.btn_file_save.width() - 10, self.height() - self.btn_file_save.height() - self.statusbar.height() - 15)
        self.richEdit.setGeometry(QRect(0, 50, self.width()-120, self.height() - 80))
        self.header.setGeometry(QRect(0, 0, self.width(), 50))
        self.btn_header_settings.move(self.width() - 30, 17)
        self.btn_clear.move(self.width() - 60, 17)

    def add_function(self):
        self.btn_connect.clicked.connect(self.connect)
        self.btn_disconnect.clicked.connect(self.disconnect)
        self.btn_file_save.clicked.connect(self.file_save)
        self.btn_header_settings.clicked.connect(self.form_settings_open)
        self.btn_clear.clicked.connect(self.clear)
        self.comboBox_baudrate.currentTextChanged.connect(self.on_selection_changed_baudrate)

    def on_threadSignal(self, text):
        #if text[:-1] == '\n' and text[:2] == '\n':
        text = text[0:-1] # удаляем последний элемент
        text = text[0:-1] # удаляем предпоследний элемент, который стал последним
        self.richEdit.appendPlainText(text) 
        self.label_1.setText(f'{self.thread.get_count_msg()}')
        # При выключении питания из файла данные удаляются
        #with open('meridian_m_log.html', 'a') as f:
        #    f.write(text)
            #f.writelines(lines)
        f = open("meridian_m_log.html", "a")
        f.write(text)
        f.close()

    def disconnect(self):
        if(self.thread and self.thread.get_state() == 1):
            self.thread.close_thread()
            self.statusbar.showMessage("Отключено", 3000)
            self.btn_state.setStyleSheet("background-color: rgb(255, 112, 93);")
 
    def connect(self):
        if self.thread.get_state() == 0:
            self.thread = WorkThread()
            self.thread.threadSignal.connect(self.on_threadSignal) 
        self.thread.start() 
        # Adding a temporary message
        self.btn_state.setStyleSheet("background-color: rgb(94, 255, 35);")
        if self.thread.get_state() == 1:
            self.statusbar.showMessage("Подключено", 3000)
            self.btn_connect.setEnabled(False)
            QTimer.singleShot(5000, lambda: self.btn_connect.setDisabled(False))
        else:
            self.statusbar.showMessage("Не удалось подключиться", 3000)

    def file_save(self):
        print("open log file")
        with open('output.html', 'w') as fout:
                fout.write(str(self.richEdit.toPlainText()))
        print("close log file")
        self.statusbar.showMessage("Файл сохранен", 3000)

    def form_settings_open(self):
        self.widget.comboBox_num_port.addItems(self.thread.serial_ports())
        self.widget.show()

    def clear(self):
        self.richEdit.clear()

    def on_selection_changed_baudrate(self):
        self.thread.set_baudrate(int(self.comboBox_baudrate.currentIndex()))
        print(self.comboBox_baudrate.currentText())
        pass

    def set_combobox_bauderate(self):
        pass
        #index = self.comboBox_baudrate.findText(str(self.thread.get_baudrate), Qt.MatchFixedString)
        #if index >= 0:
        #    self.comboBox_baudrate.setCurrentIndex(index)

    def closeEvent(self, event):
        reply = QtWidgets.QMessageBox.question(self, 'Информация',
            "Вы хотите закрыть все окна?",
             QtWidgets.QMessageBox.Yes,
             QtWidgets.QMessageBox.No)
        if reply == QtWidgets.QMessageBox.Yes:
            # Видимо надо добавлять все формы сюда
            self.widget.close()
            event.accept()
        else:
            event.ignore()