import sys
import logging
import traceback

from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QCoreApplication

from View.mainwindow import Ui_MainWindow
from View.acoustic_data_tab import AcousticDataTab
from View.signal_processing_tab import SignalProcessingTab
from View.sample_data_tab import SampleDataTab
from View.sediment_calibration_tab import SedimentCalibrationTab
from View.acoustic_inversion_tab import AcousticInversionTab
from View.note_tab import NoteTab
from View.user_manual_tab import UserManualTab
import settings as stg
from Model.read_table_for_open import ReadTableForOpen

import matplotlib.pyplot as plt
# plt.close("all")

# Check encoding used
# print(sys.getdefaultencoding())

#  python3 -m PyQt5.uic.pyuic -x QScrollbar.ui -o QScrollbar.py

PERCENT_SCREEN_SIZE = 0.85
_translate = QCoreApplication.translate

logging.basicConfig(
    level=logging.DEBUG,
    format=('[AcouSed][%(levelname)s] %(message)s')
)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

class MainApplication(QMainWindow):

    def __init__(self):
        super(MainApplication, self).__init__()

        self.ui_mainwindow = Ui_MainWindow()
        self.ui_mainwindow.setupUi(self)

        screen = QApplication.primaryScreen()
        size = screen.size()
        width = size.width()
        height = size.height()
        self.resize(int(PERCENT_SCREEN_SIZE*width), int(PERCENT_SCREEN_SIZE*height))
        try:
            # **************************************************
            # -------------- Acoustic data tab ---------------

            self.acoustic_data_tab = AcousticDataTab(self.ui_mainwindow.tab1)
            print("0 AcousticDataTab ", id(AcousticDataTab))

            self.acoustic_data_tab\
                .combobox_ABS_system_choice\
                .editTextChanged\
                .connect(
                    self.acoustic_data_tab.ABS_system_choice
                )

            # **************************************************
            # --------- Signal pre-processing data tab ----------

            self.signal_processing_tab = SignalProcessingTab(self.ui_mainwindow.tab2)

            self.signal_processing_tab.combobox_acoustic_data_choice.editTextChanged.connect(
                self.signal_processing_tab.combobox_acoustic_data_choice_change_index)

            # **************************************************.
            # --------------- Sample data tab ----------------

            self.sample_data_tab = SampleDataTab(self.ui_mainwindow.tab3)

            # **************************************************
            # ------------ Sediment calibration tab -------------

            self.sediment_calibration_tab = SedimentCalibrationTab(self.ui_mainwindow.tab4)

            # **************************************************
            # ------------ Acoustic inversion tab -------------

            self.acoustic_inversion_tab = AcousticInversionTab(self.ui_mainwindow.tab5)

            # **************************************************
            # ------------------- Note tab --------------------

            self.note_tab = NoteTab(self.ui_mainwindow.tab6)

            # **************************************************
            # ---------------- User Manual tab -----------------

            # self.user_manual_tab = UserManualTab(self.ui_mainwindow.tab7)

        # **************************************************
        # ---------------- Text File Error -----------------

        except Exception as e:
            logger.error(str(e))
            logger.error(traceback.format_exc())

            with open("Error_file.txt", "w", encoding="utf-8") as sortie:
                sortie.write(str(e))
                sortie.write(traceback.format_exc())
                # traceback.TracebackException.from_exception(e).print(file=sortie)

    def open_study_update_tabs(self):
        self.acoustic_data_tab.combobox_ABS_system_choice.setCurrentText(stg.ABS_name[0])
        self.acoustic_data_tab.fileListWidget.addFilenames(stg.filename_BS_raw_data)

        self.signal_processing_tab.combobox_acoustic_data_choice.addItems(stg.filename_BS_raw_data)

        self.sample_data_tab.fill_comboboxes_and_plot_transect()
        self.sample_data_tab.lineEdit_fine_sediment.setText(stg.filename_fine)
        self.sample_data_tab.lineEdit_fine_sediment.setToolTip(stg.path_fine)
        # self.sample_data_tab.fill_table_fine()

if __name__ == '__main__':
    # print("sys.argv:", [arg for arg in sys.argv])
    # app = MainApplication(sys.argv)
    # sys.exit(app.exec_())
    app = QApplication(sys.argv)
    window = MainApplication()
    window.show()
    # sys.exit(app.exec_())
    app.exec()
