# ============================================================================== #
    # calibration_constant_kt.py - AcouSed                                   #
    # Copyright (C) 2024  INRAE                                              #
    #                                                                        #
    # This program is free software: you can redistribute it and/or modify   #
    # it under the terms of the GNU General Public License as published by   #
    # the Free Software Foundation, either version 3 of the License, or      #
    # (at your option) any later version.                                    #
    #                                                                        #
    # This program is distributed in the hope that it will be useful,        #
    # but WITHOUT ANY WARRANTY; without even the implied warranty of         #
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          #
    # GNU General Public License for more details.                           #
    #                                                                        #
    # You should have received a copy of the GNU General Public License      #
    # along with this program.  If not, see <https://www.gnu.org/licenses/>. #

    #                                                      by Brahim MOUDJED #
# ============================================================================== #


from os import path
import pandas as pd
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QDialog, QTabWidget, QGridLayout, QScrollArea,
                             QFileDialog, QMessageBox, QLabel)
from PyQt5.QtCore import Qt

class CalibrationConstantKt(QDialog):

    def __init__(self, parent=None):

        super(CalibrationConstantKt, self).__init__(parent)

        self.setGeometry(400, 200, 300, 400)

        self.setWindowTitle("Calibration constant kt")

        self.verticalLayout_Main = QVBoxLayout()

        self.tab = QTabWidget()
        self.verticalLayout_Main.addWidget(self.tab)

        try:
            self.data_ABS = pd.read_excel("ABS_calibration_constant_kt.xlsx", header=0, sheet_name=None)

        except FileNotFoundError as e:

            msgBox = QMessageBox()
            msgBox.setWindowTitle("File Not Found Error")
            msgBox.setIcon(QMessageBox.Warning)
            msgBox.setText("Please check Excel file name for the calibration constant kt \n"
                           "It should be an excel file named : 'ABS_calibration_constant_kt.xlsx'")
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec()

        self.setLayout(self.verticalLayout_Main)
        self.load_freq_and_kt_values()

    def open_dialog_box(self):
        filename = QFileDialog.getOpenFileNames(self, "Calibration file", "", "Calibration file (*.xlsx)",
                                                options=QFileDialog.DontUseNativeDialog)
        print(filename)
        dir_name = path.dirname(filename[0][0])
        file_name = path.basename(filename[0][0])
        print(f"dir name : {dir_name} & file name : {file_name}")

        self.data_ABS = pd.read_excel(dir_name + "/" + file_name)

        self.lineEdit_file.setText(file_name)

        self.load_freq_and_kt_values()

    def load_freq_and_kt_values(self):

        for t in range(len(self.data_ABS.keys())):
            self.tab.removeTab(t)

        for t_index, t_value in enumerate(list(self.data_ABS.keys())):

            exec("self.tab_calib_" + str(t_index) + "= QWidget()")
            eval("self.tab.addTab(self.tab_calib_" + str(t_index) + ", '" + str(t_value) + "')")

            exec("self.verticalLayout_tab_" + str(t_index) + "= QVBoxLayout(self.tab_calib_" + str(t_index) + ")")

            exec("self.scrollarea_tab_" + str(t_index) + " = QScrollArea(self.tab_calib_" + str(t_index) + ")")
            eval("self.scrollarea_tab_" + str(t_index) + ".setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)")
            eval("self.scrollarea_tab_" + str(t_index) + ".setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)")
            eval("self.scrollarea_tab_" + str(t_index) + ".setWidgetResizable(True)")

            eval("self.verticalLayout_tab_" + str(t_index) + ".addWidget(self.scrollarea_tab_" + str(t_index) + ")")

            exec("self.gridLayout_tab_" + str(t_index) + " = QGridLayout(self.scrollarea_tab_" + str(t_index) + ")")
            if [*self.data_ABS.values()][t_index].columns.any():
                exec("self.label_freq_" + str(t_index) + " = QLabel('" + str([*self.data_ABS.values()][t_index].columns[0]) + " (MHz)')")
                exec("self.label_kt_" + str(t_index) + " = QLabel('" + str([*self.data_ABS.values()][t_index].columns[1]) + " (V.m<sup>1.5</sup>)')")
            else:
                exec("self.label_freq_" + str(t_index) + " = QLabel('Frequency (MHz)')")
                exec("self.label_kt_" + str(t_index) + " = QLabel('kt (V.m<sup>1.5</sup>)')")
            eval("self.gridLayout_tab_" + str(t_index) + ".addWidget(self.label_freq_" + str(t_index) + ", 0, 0, 1, 1, Qt.AlignCenter)")
            eval("self.gridLayout_tab_" + str(t_index) + ".addWidget(self.label_kt_" + str(t_index) + ", 0, 1, 1, 1, Qt.AlignCenter)")

            for x in range(self.data_ABS[t_value].shape[0]):
                exec("self.label_freq_" + str(x) + "_ABS_" + str(t_index) + " = QLabel()")
                # print(eval("self.label_freq_" + str(x) + "_ABS_" + str(t_index) + ".setText('" + str(self.data_ABS[t_value].iloc[x][0]*1e-6) + " MHz')"))
                eval("self.label_freq_" + str(x) + "_ABS_" + str(t_index) + ".setText('" + str(self.data_ABS[t_value].iloc[x][0]*1e-6) + " (MHz)')")
                # eval("self.label_freq_" + str(x) + "_ABS_" + str(t_index) + ".setDisabled(True)")
                eval("self.gridLayout_tab_" + str(t_index) + ".addWidget(self.label_freq_" + str(x) + "_ABS_" + str(t_index) +
                     ", " + str(x + 1) + ", 0, 1, 1,Qt.AlignCenter)")
                exec("self.label_kt_" + str(x) + "_ABS_" + str(t_index) + " = QLabel()")
                exec("self.label_kt_" + str(x) + "_ABS_" + str(t_index) + ".setText('" + str(self.data_ABS[t_value].iloc[x][1]) + "V.m<sup>1.5</sup>')")
                eval("self.label_kt_" + str(x) + "_ABS_" + str(t_index) + ".setStyleSheet('border: 1px solid black;')")
                eval("self.gridLayout_tab_" + str(t_index) + ".addWidget(self.label_kt_" + str(x) + "_ABS_" + str(t_index) +
                     ", " + str(x+1) + ", 1, 1, 1, Qt.AlignCenter)")

