# ============================================================================== #
    # 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 #
# ============================================================================== #


import os
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
        )

        dir_name = os.path.dirname(filename[0][0])
        file_name = os.path.basename(filename[0][0])
        print(f"dir name : {dir_name} & file name : {file_name}")

        self.data_ABS = pd.read_excel(os.path.join(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())):
            tab_calib = QWidget()
            self.tab.addTab(tab_calib, t_value)

            verticalLayout = QVBoxLayout(tab_calib)

            scrollarea = QScrollArea(tab_calib)
            scrollarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
            scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
            scrollarea.setWidgetResizable(True)

            verticalLayout.addWidget(scrollarea)
            gridLayout = QGridLayout(scrollarea)

            if [*self.data_ABS.values()][t_index].columns.any():
                label_freq = QLabel(
                    f"{[*self.data_ABS.values()][t_index].columns[0]} (MHz)"
                )
                label_kt = QLabel(
                    f"{[*self.data_ABS.values()][t_index].columns[1]} "
                    + "(V.m<sup>1.5</sup>)"
                )
            else:
                label_freq = QLabel('Frequency (MHz)')
                label_kt = QLabel('kt (V.m<sup>1.5</sup>)')

            gridLayout.addWidget(
                label_freq, 0, 0, 1, 1, Qt.AlignCenter
            )
            gridLayout.addWidget(
                label_kt, 0, 1, 1, 1, Qt.AlignCenter
            )

            for x in range(self.data_ABS[t_value].shape[0]):
                label_freq_ABS = QLabel()

                label_freq_ABS.setText(
                    f"{self.data_ABS[t_value].iloc[x][0]*1e-6}" + "(MHz)"
                )
                gridLayout.addWidget(
                    label_freq_ABS, x + 1, 0, 1, 1,Qt.AlignCenter
                )

                label_kt_ABS = QLabel()

                label_kt_ABS.setText(
                    f"{self.data_ABS[t_value].iloc[x][1]} V.m<sup>1.5</sup>"
                )
                label_kt_ABS.setStyleSheet('border: 1px solid black;')
                gridLayout.addWidget(
                    label_kt_ABS, x + 1 , 1, 1, 1, Qt.AlignCenter
                )
