#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 qgis.core import QgsVectorLayer, QgsField, QgsFeature, QgsMapLayerRegistry, QgsFeatureRequest
from qgis.core import QgsGraduatedSymbolRendererV2, QgsProject, QgsRendererRangeV2, QgsSymbolV2
from PyQt4.Qt import QSqlQuery

from AKFeatureResultsMapChem import AKFeatureResultsMapChem
from AKSettings import TABLES

class AKFeatureResultsMapNormative(AKFeatureResultsMapChem):
    '''
    This feature provides the functionality for the second form to create normative maps. 
    '''
    def __init__(self, settings, iface, windowTitle = "Normative Map Results", parent=None):
        super(AKFeatureResultsMapNormative, self).__init__(settings, iface, windowTitle = windowTitle, parent=parent)

        self.m_form.plotButton.setText("Normative Map")
        self.normativeId = 1
        self.defineSQLQueries()

    def defineSQLQueries(self):
        self.sqlSelNormLimits = "SELECT " \
                                    "limMinNorm, limMedNorm, limMaxNorm " \
                                "FROM " + \
                                    TABLES.CHEMNORMPARAMS + " CNP " \
                                "WHERE " \
                                    "normativeId = ? " \
                                    "AND hydrochemicalParametersCode = ? ;"

    def getNormLimits(self, normativeId, paramId):
        returnValues = []
        if normativeId != None: 
            query = QSqlQuery(self.currentDB)
            query.prepare(self.sqlSelNormLimits)
            query.addBindValue(normativeId)
            query.addBindValue(paramId)
            query.exec_()
            while query.next():
                minValue = query.value(0)
                medValue = query.value(1)
                maxValue = query.value(2)
                returnValues.append(minValue)
                returnValues.append(medValue)
                returnValues.append(maxValue)
        return returnValues
    
    def calcParamLimits(self, layers, targetFieldIndex):
        paramLimits = {}
        for paramId in layers:
            layer = layers[paramId]
            paramLimits[paramId] = self.getNormLimits(self.normativeId, paramId)
            if len(paramLimits[paramId]) > 0:
                paramLimits[paramId].insert(0,min(paramLimits[paramId][0],layer.minimumValue(targetFieldIndex))) # add lowest class limit
                paramLimits[paramId].append(max(layer.maximumValue(targetFieldIndex), paramLimits[paramId][-1])) # add highest class limit
        return paramLimits
    
    def finalizeLayers(self, newlayers, targetField, groupNode, paramLimits=None, addLegend = True):
        targetIndex = self.getTargetIndex(targetField)
        self.paramLimits = self.calcParamLimits(newlayers, targetIndex) 
        labels = ["<Min", "Min-Med", "Med-Max", ">Max"]
        super(AKFeatureResultsMapNormative, self).finalizeLayers(newlayers, targetField, groupNode, self.paramLimits, labels, addLegend)
        
        #QMessageBox.information(self.iface.mainWindow(),
            #"Finished creating the normative map(s).",
            #"The following maps have been generated: \n\n- " + "\n- ".join(newlyGeneratedMaps))