# Copyright (c) 2011-2014, B.I.Stepanov Institute of Physics, National Academy
# of Sciences of Belarus.
#
# 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 2 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, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from common.utils import txt
from common.utils import utils

from common.FileSelectionWidget import *
from common.StatusSignalingWidget import *

from PreparedLidarInput import *

__all__ = ['LidarDatabaseWidget']

# *****************************************************************************
class LidarDatabaseWidget(StatusSignalingWidget):
    """Widget responsible for loading of lidar input data in the manual version
    of aerosol profile retrieval algorithm."""

    # ---- Signals ------------------------------------------------------------
    dataListChanged = pyqtSignal()

    # ---- Public methods -----------------------------------------------------
    def __init__(self, parent = None):
        StatusSignalingWidget.__init__(self, parent)

        # ---- Members ----
        # List of 'PreparedLidarInput' instances loaded from the currently
        # selected database file.
        self.dataList = []

        # ---- Layout ----
        layout = QVBoxLayout()

        self.fileSelector = FileSelectionWidget(
            '&Lidar input:',
            'Microsoft Access databases (*.mdb)',
            'Select lidar input database',
            'Open an existing lidar input database file')
        self.fileSelector.showReloadButton(
            'Reload the currently selected lidar input database')
        self.fileSelector.fileOpened.connect(self.onFileOpened)
        layout.addWidget(self.fileSelector)

        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

    def getDataList(self):
        """Return the list of 'PreparedLidarInput' instances loaded from the
        currently selected database file.

        If no data have been loaded, an empty list is returned."""

        return self.dataList

    def saveSettings(self, settings):
        with utils.SettingsGrouper(settings, 'LidarDatabaseWidget'):
            self.fileSelector.saveSettings(settings, 'filePath')

    def loadSettings(self, settings):
        with utils.SettingsGrouper(settings, 'LidarDatabaseWidget'):
            self.fileSelector.loadSettings(settings, 'filePath')

    # ---- Private slots ------------------------------------------------------
    def onFileOpened(self):
        """Load the currently selected lidar database.

        If the database file is malformed or not accessible, clear the data and
        report an error describing the situation."""

        # Remove the old data, if any.
        del self.dataList[:]

        self.dataListChanged.emit()

        filePath = self.fileSelector.getFilePath()

        if filePath is None:
            self.setErrorMessage('Lidar input database is not selected')
            return

        try:
            # This message will be cleared by 'setErrorMessage' later on.
            self.setProgressMessage('Loading lidar database...', True)
            self.dataList = PreparedLidarInput.readDataList(filePath)

        except txt.Error as e:
            self.setErrorMessage(e.text)
            return

        self.clearStatusMessage()
        self.dataListChanged.emit()
