import os
from PyQt5 import QtWidgets
from .qtd import Ui_MainWindow
from ..utils import SpinBoxFixStyle
from ..version import __version__
from ..citation import __citation__
from ..utils import InformationBox
# exec(open(os.path.join(os.path.curdir, 'version.py')).read())
# exec(open(os.path.join(os.path.curdir, 'citation.py')).read())


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    """
    Main window
    """

    def __init__(self, parent=None):
        # initialization of the superclass
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)  # setup the GUI --> function generated by pyuic5
        try:
            env = os.environ['CONDA_DEFAULT_ENV']
        except:
            env = 'unknown'
        self.setWindowTitle("PeakPo ver. " + str(__version__) + " on " + env)
        #
        self.build_ui()
        self.connect_channel()
        # the two lines needs to be considred for move from this widget file
        self.actionCiting_PeakPo.triggered.connect(self.about)
        self.actionShortcut_keys.triggered.connect(self.shortcutkeys)

    def build_ui(self):
        # self.pushButton_MakeBasePtn.setEnabled(False)
        """ This was unstable feature but from 06/18/2022 it is enabled.
        self.pushButton_SetJCPDSStepTo0001.setDisabled(True)
        self.pushButton_SetJCPDSStepTo001.setDisabled(True)
        self.pushButton_SetJCPDSStepTo01.setDisabled(True)
        self.pushButton_UpdateJCPDSSteps.setDisabled(True)
        self.doubleSpinBox_JCPDSStep.setDisabled(True)
        """
        self.doubleSpinBox_JCPDSStep.setKeyboardTracking(False)
        self.doubleSpinBox_JCPDSStep.setStyle(SpinBoxFixStyle())
        self.doubleSpinBox_Pressure.setKeyboardTracking(False)
        self.doubleSpinBox_Pressure.setStyle(SpinBoxFixStyle())
        self.doubleSpinBox_Temperature.setKeyboardTracking(False)
        self.doubleSpinBox_Temperature.setStyle(SpinBoxFixStyle())
        self.spinBox_BGParam0.setKeyboardTracking(False)
        self.spinBox_BGParam1.setKeyboardTracking(False)
        self.spinBox_BGParam2.setKeyboardTracking(False)
        self.spinBox_BGParam0.setStyle(SpinBoxFixStyle())
        self.spinBox_BGParam1.setStyle(SpinBoxFixStyle())
        self.spinBox_BGParam2.setStyle(SpinBoxFixStyle())
        self.doubleSpinBox_Background_ROI_max.setKeyboardTracking(False)
        self.doubleSpinBox_Background_ROI_min.setKeyboardTracking(False)
        self.doubleSpinBox_Background_ROI_max.setStyle(SpinBoxFixStyle())
        self.doubleSpinBox_Background_ROI_min.setStyle(SpinBoxFixStyle())
        self.doubleSpinBox_SetWavelength.setKeyboardTracking(False)
        self.doubleSpinBox_SetWavelength.setStyle(SpinBoxFixStyle())
        linethicknesses = ['0', '0.1', '0.2', '0.5', '0.75',
                           '1', '1.5', '2', '3', '4', '5']
        self.comboBox_BasePtnLineThickness.addItems(linethicknesses)
        self.comboBox_PtnJCPDSBarThickness.addItems(linethicknesses)
        self.comboBox_CakeJCPDSBarThickness.addItems(linethicknesses)
        self.comboBox_BkgnLineThickness.addItems(linethicknesses)
        self.comboBox_WaterfallLineThickness.addItems(linethicknesses)
        self.comboBox_VertCursorThickness.addItems(linethicknesses)
        self.comboBox_BasePtnLineThickness.setCurrentText('1')
        self.comboBox_PtnJCPDSBarThickness.setCurrentText('1')
        self.comboBox_CakeJCPDSBarThickness.setCurrentText('0.5')
        self.comboBox_BkgnLineThickness.setCurrentText('0.5')
        self.comboBox_WaterfallLineThickness.setCurrentText('0.5')
        self.comboBox_VertCursorThickness.setCurrentText('1')
        fontsizes = ['4', '6', '8', '10', '12', '14', '16', '18', '20', '24',
                     '28', '36', '42']
        self.comboBox_HKLFontSize.addItems(fontsizes)
        self.comboBox_HKLFontSize.setCurrentText('8')
        self.comboBox_PnTFontSize.addItems(fontsizes)
        self.comboBox_PnTFontSize.setCurrentText('16')
        self.comboBox_Symmetry.addItems(['cubic', 'tetragonal',
                                         'hexagonal', 'orthorhombic'])
        self.comboBox_Symmetry.setCurrentText('cubic')
        self.tableWidget_DiffImgAzi.\
            setHorizontalHeaderLabels(['Notes', '2th', 'Azi', '2th', 'Azi'])
        # navigation toolbar modification
        """
        self.ntb_WholePtn = QtWidgets.QPushButton()
        self.ntb_WholePtn.setText("Z")
        self.ntb_WholePtn.setToolTip("Zoom Out")
        self.mpl.ntb.addWidget(self.ntb_WholePtn)
        self.ntb_SaveSession = QtWidgets.QPushButton()
        self.ntb_SaveSession.setText("S")
        self.ntb_SaveSession.setToolTip("Save dpp and ppss")
        self.mpl.ntb.addWidget(self.ntb_SaveSession)
        self.ntb_toPkFt = QtWidgets.QPushButton()
        self.ntb_toPkFt.setText("toPkFt")
        self.mpl.ntb.addWidget(self.ntb_toPkFt)
        self.ntb_fromPkFt = QtWidgets.QPushButton()
        self.ntb_fromPkFt.setText("fromPkFt")
        self.mpl.ntb.addWidget(self.ntb_fromPkFt)
        self.ntb_ResetY = QtWidgets.QCheckBox()
        self.ntb_ResetY.setCheckable(True)
        self.ntb_ResetY.setChecked(False)
        self.ntb_ResetY.setText("AutoYScale")
        self.mpl.ntb.addWidget(self.ntb_ResetY)
        self.ntb_Bgsub = QtWidgets.QCheckBox()
        self.ntb_Bgsub.setCheckable(True)
        self.ntb_Bgsub.setChecked(True)
        self.ntb_Bgsub.setText("BgSub")
        self.mpl.ntb.addWidget(self.ntb_Bgsub)
        self.ntb_NightView = QtWidgets.QCheckBox()
        self.ntb_NightView.setCheckable(True)
        self.ntb_NightView.setChecked(True)
        self.ntb_NightView.setText("Night")
        self.mpl.ntb.addWidget(self.ntb_NightView)
        """

    def closeEvent(self, event):
        self.deleteLater()
        event.accept()

    def connect_channel(self):
        self.pushButton_RoomT.clicked.connect(
            lambda: self.set_temperature(300))
        self.pushButton_S_RoomT.clicked.connect(
            lambda: self.set_temperature(300))
        self.pushButton_1bar.clicked.connect(
            lambda: self.set_pressure(0.0))
        self.pushButton_SetPStepTo1.clicked.connect(
            lambda: self.set_q_pstep(1.))
        self.pushButton_SetPStepTo10.clicked.connect(
            lambda: self.set_q_pstep(10.))
        self.pushButton_SetTStepTo100.clicked.connect(
            lambda: self.set_q_tstep(100))
        self.pushButton_SetTStepTo1000.clicked.connect(
            lambda: self.set_q_tstep(1000))
        self.doubleSpinBox_PStep.valueChanged.connect(self.set_pstep)
        self.spinBox_TStep.valueChanged.connect(self.set_tstep)
        """
        self.pushButton_SetUCFitStepTo0_01.clicked.connect(
            lambda: self.set_ustep(0.01))
        self.pushButton_SetUCFitStepTo0_001.clicked.connect(
            lambda: self.set_ustep(0.001))
        self.pushButton_SetUCFitStepTo0_0001.clicked.connect(
            lambda: self.set_ustep(0.0001))
        """
        self.pushButton_SetJCPDSStepTo0001.clicked.connect(
            lambda: self.set_jstep(0.001))
        self.pushButton_SetJCPDSStepTo001.clicked.connect(
            lambda: self.set_jstep(0.01))
        self.pushButton_SetJCPDSStepTo01.clicked.connect(
            lambda: self.set_jstep(0.1))
        self.pushButton_AboutPeakpo.clicked.connect(self.about)
        self.pushButton_Help.clicked.connect(self.shortcutkeys)

    """
    def set_ustep(self, value):
        self.doubleSpinBox_UCFitStep.setValue(value)
    """

    def set_jstep(self, value):
        self.doubleSpinBox_JCPDSStep.setValue(value)

    def set_pstep(self):
        self.doubleSpinBox_Pressure.setSingleStep(
            self.doubleSpinBox_PStep.value())

    def set_tstep(self):
        self.doubleSpinBox_Temperature.setSingleStep(
            self.spinBox_TStep.value())

    def set_temperature(self, temperature):
        self.doubleSpinBox_Temperature.setValue(temperature)

    def set_pressure(self, pressure):
        self.doubleSpinBox_Pressure.setValue(pressure)

    def set_q_pstep(self, value=1.):
        self.doubleSpinBox_PStep.setValue(value)

    def set_q_tstep(self, value=1000.):
        self.spinBox_TStep.setValue(value)

    def about(self):
        information = 'PeakPo ver.' + __version__ + '<br>' + \
            'A Visual Diffraction Analysis Tool<br>' + \
            'by S.-H. Dan Shim, SHDShim@gmail.com<br>' + \
            'Arizona State University<br><br>' + \
            'Source: https://github.com/SHDShim/peakpo-v7 <br><br>' + \
            'Manual: https://github.com/SHDShim/PeakPo/wiki <br><br>' + \
            'how to cite: ' + str(__citation__) + '<br><br>' + \
            'WARNING. Use at your own risk. ' + \
            'This is a free software and no support is provided.<br>'
        infobox = InformationBox(title="About PeakPo")
        infobox.setText(information)
        infobox.exec_()

        """
        self.textEdit_about.setText(
            'PeakPo ver.' + __version__ + '<br>' +
            'A Visual Diffraction Analysis Tool<br>' +
            'by S.-H. Dan Shim, SHDShim@gmail.com<br>' +
            'Arizona State University<br><br>' +
            'Source: https://github.com/SHDShim/peakpo-v7 <br><br>' +
            'Manual: https://github.com/SHDShim/PeakPo/wiki <br><br>'
            'how to cite: ' + str(__citation__) + '<br><br>'
            'WARNING. Use at your own risk. ' +
            'This is a free software and no support is provided.<br>')
        """

    def shortcutkeys(self):
        information = '** Shortcut Keys ** <br><br>' + \
            'To activate shortcut keys: <br>' + \
            ' - Mouse click the plotting area. <br>' + \
            ' - Make sure no toolbar buttons are in blue. <br><br>' + \
            'Save session: s<br>' + \
            'Rescale vertical: v<br>' + \
            'Whole spectrum: w<br>' + \
            'Home or Reset: H or R<br>' + \
            'Back: left arrow<br>' + \
            'Forward: right arrow<br>' + \
            'Pan: p<br>' + \
            'Zoom: o<br>' + \
            'Peak position read: i<br>' + \
            'Constrain pan/zoom to x axis: hold x when panning/zooming<br>' + \
            'Constrain pan/zoom to y axis: hold y when panning/zooming<br>' + \
            'Preserve aspect ratio: hold CTRL when panning/zooming<br>' + \
            'Toggle x scale (log/lin): L or k when mouse is over an axes<br>' + \
            'Toggle y scale (log/lin): l when mouse is over an axes<br>'
        infobox = InformationBox(title="Help")
        infobox.setText(information)
        infobox.exec_()

        """
        self.textEdit_shortcuts.setText(
            '** Shortcut Keys ** <br><br>' +
            'To activate shortcut keys: <br>' +
            ' - Mouse click the plotting area. <br>' +
            ' - Make sure no toolbar buttons are in blue. <br><br>' +
            'Save session: s<br>' +
            'Rescale vertical: v<br>' +
            'Whole spectrum: w<br>' +
            'Home or Reset: H or R<br>' +
            'Back: left arrow<br>' +
            'Forward: right arrow<br>' +
            'Pan: p<br>' +
            'Zoom: o<br>' +
            'Peak position read: i<br>' +
            'Constrain pan/zoom to x axis: hold x when panning/zooming<br>' +
            'Constrain pan/zoom to y axis: hold y when panning/zooming<br>' +
            'Preserve aspect ratio: hold CTRL when panning/zooming<br>' +
            'Toggle x scale (log/lin): L or k when mouse is over an axes<br>' +
            'Toggle y scale (log/lin): l when mouse is over an axes<br>')
        """
