#coding=utf-8
#Copyright (C) 2015 IDAEA-CSIC
#
#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
#ITHOUT 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
'''
:copyright: Copyright (C) 2015 IDAEA-CSIC
:authors: V. Velasco Mansilla, L.M. de Vries, A. Nardi, R. Criollo, E. Vázquez Suñé
:contact: enric.vazquez@idaea.csic.es
:license: GPL General Public License, version 2 or any later version (http://opensource.org/licenses/GPL-2.0)
'''
from PyQt4.QtGui import QIcon
from PyQt4.Qt import QSqlQueryModel, QSqlQuery

from results.AKFeatureResultsMapNormative import AKFeatureResultsMapNormative
from form.AKFormNormative import AKFormNormative
from AKSettings import TABLES
from AKFeatureCustomChartChem import AKFeatureCustomChartChem

class AKFeatureMapNormative(AKFeatureCustomChartChem):
    def __init__(self, settings, iface, parent=None):
        super(AKFeatureMapNormative, self).__init__(settings, iface, windowTitle='Normative Map Measurements', parent=parent)

        self.m_icon = QIcon(settings.getIconPath('parameterNormativeMap.png'))
        self.m_text = 'Parameter Normative Map'

        self.m_form = AKFormNormative(iface, self.parent())
        self.m_form.accepted.connect(self.onNormativeSelected)
        self.m_form.cmbNormative.currentIndexChanged.connect(self.onNormativeChanged)
        self.m_measurementsSubFeature.m_parametersAreImposed = False
        self.m_plotSubFeature = AKFeatureResultsMapNormative(self.m_settings, self.iface, parent = self.m_measurementsSubFeature.m_form.window())
        self.defineSQLQueries()

    def defineSQLQueries(self):
        super(AKFeatureMapNormative, self).defineSQLQueries()
        self.sqlSelAllNormatives =  "SELECT " \
                                        "NRM.id, " \
                                        "NRM.normative, " \
                                        "RSP.organisationName, " \
                                        "NRM.date, " \
                                        "NRM.otherNormativesDetails, " \
                                        "NRM.observations " \
                                    "FROM " + \
                                        TABLES.NORMATIVES + " NRM " + \
                                        "LEFT JOIN " + TABLES.RESPONSIBLES + " RSP " \
                                            "ON NRM.responsiblePartyId = RSP.id " \
                                    "ORDER BY NRM.normative COLLATE NOCASE;"

        self.sqlSelNormativeParams =  "SELECT " \
                                        "PRMS.parameterNumber " \
                                    "FROM " + \
                                        TABLES.CHEMNORMPARAMS + " NRMPRMS, " + \
                                        TABLES.CHEMPARAMS + " PRMS " \
                                    "WHERE " \
                                        "NRMPRMS.normativeId = ? " \
                                        "AND NRMPRMS.hydrochemicalParametersCode = PRMS.id " \
                                    "ORDER BY PRMS.normative COLLATE NOCASE;"

    def initialize(self):
        self.currentDB = self.m_settings.getCurrentDB()
        self.getNormativeData()
        self.m_form.show()

    def onNormativeSelected(self):
        normsCombo = self.m_form.cmbNormative
        curIndex = normsCombo.currentIndex()
        normativeId = normsCombo.model().data(normsCombo.model().index(curIndex,0))
        baseParams = self.getNormativeParameters(normativeId)
        self.m_measurementsSubFeature.normativeId = normativeId
        self.m_measurementsSubFeature.availableParams = baseParams
        labelText = 'Available Parameters in "' + self.m_form.cmbNormative.currentText() + "' Normative:"
        self.m_measurementsSubFeature.m_form.lblAvailableParams.setText(labelText)
        self.m_plotSubFeature.normativeId = normativeId
        super(AKFeatureMapNormative, self).initialize()

    def onNormativeChanged(self):
        normsCombo = self.m_form.cmbNormative
        curIndex = normsCombo.currentIndex()
        responsible = normsCombo.model().data(normsCombo.model().index(curIndex,2))
        date = normsCombo.model().data(normsCombo.model().index(curIndex,3))
        details = normsCombo.model().data(normsCombo.model().index(curIndex,4))
        observations = normsCombo.model().data(normsCombo.model().index(curIndex,5))
        if(responsible != None):
            self.m_form.txtResponsible.setText(responsible)
        else:
            self.m_form.txtResponsible.clear()
        if(date != None):
            self.m_form.txtDate.setText(date)
        else:
            self.m_form.txtDate.clear()

        if(details != None):
            self.m_form.txtDetails.setPlainText(details)
        else:
            self.m_form.txtDetails.clear()
        if(observations != None):
            self.m_form.txtObservations.setPlainText(observations)
        else:
            self.m_form.txtObservations.clear()

    def getNormativeData(self):
        query = QSqlQuery(self.currentDB)
        query.prepare(self.sqlSelAllNormatives)
        query.exec_()
        normsModel = QSqlQueryModel(self.m_form)
        normsModel.setQuery(query)
        while normsModel.canFetchMore():
            normsModel.fetchMore()
        self.m_form.cmbNormative.setModel(normsModel)
        NORMATIVE = 1
        self.m_form.cmbNormative.setModelColumn(NORMATIVE)

    def getNormativeParameters(self, normativeId):
        query = QSqlQuery(self.currentDB)
        query.prepare(self.sqlSelNormativeParams)
        query.addBindValue(normativeId)
        query.exec_()
        baseParamList = []
        while query.next():
            baseParameter = query.value(0)
            baseParamList.append(baseParameter)
        return baseParamList
