#  Copyright 2017 Carlos Pascual-Izarra <cpascual@users.sourceforge.net>
#
#  This file is part of PeakEvo.
#
#  PeakEvo 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.
#
#  PeakEvo 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 Foobar.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import absolute_import

import sys
import os
import logging
from qtpy import QtWidgets, QtGui, uic
from .configuration import BaseConfigurableClass


class AcqSettings(QtWidgets.QWidget, BaseConfigurableClass):
    """A widget for setting the acquisition parameters"""

    ACQ_DEADTIME_MS = 500

    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent=parent)
        BaseConfigurableClass.__init__(self)

        # load ui
        uipath = os.path.join(os.path.dirname(__file__), "acqsettings.ui")
        uic.loadUi(uipath, self)

        # set icons:
        self.outDirBT.setIcon(QtGui.QIcon("icons:document-open.svg"))
        self.autoAcqTimeBT.setIcon(QtGui.QIcon("icons:zoom-fit-height.svg"))

        # connect signals
        self.acqTimeSB.valueChanged[float].connect(self._onAcqTimeChanged)
        self.referenceBT.toggled.connect(self._onRefToggled)
        self.backgroundBT.toggled.connect(self._onRefToggled)
        self.outDirBT.clicked.connect(self._onOutDirBTClicked)
        self.pCalibBT.clicked.connect(self._onPressureCalib)

        # register config properties
        self.registerConfigProperty(self.outDirLE.text, self.outDirLE.setText, "outDir")
        self.registerConfigProperty(
            self.nameSuffixLE.text, self.nameSuffixLE.setText, "nameSuffix"
        )
        self.registerConfigProperty(
            self.acqPeriodSB.value, self.acqPeriodSB.setValue, "acqPeriod"
        )
        self.registerConfigProperty(
            self.acqTimeSB.value, self.acqTimeSB.setValue, "acqTime"
        )
        # self.registerConfigProperty(self.referenceLE.text,
        #                             self.referenceLE.setText,
        #                             'referenceFile')
        # self.registerConfigProperty(self.backgroundLE.text,
        #                             self.backgroundLE.setText,
        #                             'backgroundFile')
        self.registerConfigProperty(
            self.pressurePortCB.currentText, self._setPressurePortCBText, "pressurePort"
        )
        self.registerConfigProperty(
            self.pCalibLE.text, self._setPressureCalib, "pressureCalib"
        )

    def _setPressurePortCBText(self, text):
        self.pressurePortCB.setEditText(text)
        self.pressurePortCB.activated[str].emit(text)

    def _setPressureCalib(self, text):
        self.pCalibLE.setText(text)

    def _onAcqTimeChanged(self, ms):
        """Adjust the acquisition period if necessary (consider dead time)"""
        minPeriod = (ms + self.ACQ_DEADTIME_MS) / 1000
        self.acqPeriodSB.setMinimum(minPeriod)
        if self.acqPeriodSB.value() < minPeriod:
            self.acqPeriodSB.setValue(minPeriod)
            logging.info("Auto-increasing acquisition period to %f", minPeriod)

    def _onRefToggled(self, checked):
        self.acqTimeSB.setEnabled(
            not self.referenceBT.isChecked() and not self.backgroundBT.isChecked()
        )

    def _onOutDirBTClicked(self):
        dir = QtWidgets.QFileDialog.getExistingDirectory(
            self, "Output Dir", self.outDirLE.text()
        )
        if dir:
            self.outDirLE.setText(dir)

    def _onPressureCalib(self):
        pSensor = self.parent().parent()._pressureSensor
        from .pressurecalib import PressureCalib

        calibDlg = PressureCalib(pSensor, parent=self)
        ok = calibDlg.exec_()
        if ok:
            ctext = " ".join(["%.6f" % e for e in calibDlg.calib])
            self._setPressureCalib(ctext)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    w = AcqSettings()
    w.show()

    sys.exit(app.exec_())
