#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 QgsField, QgsFeature, QgsFeatureRequest, QgsProject
from PyQt4.QtCore import QVariant
from PyQt4.Qt import QMessageBox

from AKFeatureResults import AKFeatureResults
from form.AKWidgetGeneralMapSettings import AKWidgetGeneralMapSettings
from AKSettings import TABLES

class AKFeatureResultsMap(AKFeatureResults):
    '''
    This feature provides the functionality for the second form to create maps. 
    '''
    def __init__(self, settings, iface, windowTitle = "Map Results", parent=None):
        super(AKFeatureResultsMap, self).__init__(settings, iface, windowTitle, parent=parent)
                
        self.paramLimits = None
        self.paramValueLimits = {}
        self.addLegend = True
        self.newLayers = {}
        
    def customizeForm(self):
        super(AKFeatureResultsMap, self).customizeForm()
           
        self.mapSettingsForm = AKWidgetGeneralMapSettings(self.iface, self.m_form)  
        self.m_form.customResultsGroup.show()
        self.m_form.customResultsGroup.setTitle("Map settings")
        
        self.m_form.customResultsGroup.layout().addWidget(self.mapSettingsForm)
        self.m_form.plotButton.setText("Map")      

    def initialize(self, showTable=True):
        if(showTable):
            self.showData()
        super(AKFeatureResultsMap, self).initialize()
        
    def onActionClicked(self):
        targetField = self.getTargetField()
        timeSeriesData = self.storeDataInTimeSeries()
        pointsLayer = self.m_settings.m_availableTables[TABLES.POINTS]["layerObject"]
        pointsProjection = self.getProjection(pointsLayer)
        newlyGeneratedMaps = []
        root = QgsProject.instance().layerTreeRoot()
        groupName = self.generateNewName("Generated Maps")
        newGroupNode = root.addGroup(groupName)
        for unitId in timeSeriesData:
            allNewLayers = {}           
            curUnitInfo = timeSeriesData[unitId]
            for i in range(len(curUnitInfo["parameterIds"])):
                paramId = curUnitInfo["parameterIds"][i]
                paramName = curUnitInfo["parameterNames"][i]
                units = curUnitInfo["valuesLabel"]
                attrFields = [QgsField("paramName", QVariant.String), 
                              QgsField("earliest",  QVariant.Double),
                              QgsField("latest", QVariant.Double),
                              QgsField("mean", QVariant.Double),
                              QgsField("minimum", QVariant.Double),
                              QgsField("maximum", QVariant.Double)]
                labelPlacement = 0
                mapName = paramName + " (" + units + ")"
                newlyGeneratedMaps.append(mapName)
                allNewLayers[paramId] = self.addVectorLayer("Point", mapName, pointsProjection, attrFields, labelPlacement)
           
            pointsLayer = self.m_settings.m_availableTables[TABLES.POINTS]["layerObject"]
            for seriesId in curUnitInfo["series"]:
                curSeries = curUnitInfo["series"][seriesId]
                paramId = curSeries["parameterId"]
                paramName = curSeries["parameterName"]
                curLayer = None
                curLayer = allNewLayers[paramId]
                curProvider = curLayer.dataProvider() 

                pointId = curSeries["pointId"]
                featureRequest = QgsFeatureRequest().setFilterFid( pointId )
                requestedFeaturesIterator = pointsLayer.getFeatures(featureRequest)
                pointFeatures = [f for f in requestedFeaturesIterator]
                pointFeature = pointFeatures[0]
                pointGeometry = pointFeature.geometry()
                feature = QgsFeature()
                feature.setGeometry(pointGeometry)
                point = curSeries["point"]
                paramName = curSeries["parameterName"]
                values = curSeries["values"]
                targetFields = self.getStatistics(values)
                feature.setAttributes([point, paramName, 
                                       targetFields["earliest"],
                                       targetFields["latest"],
                                       targetFields["mean"],
                                       targetFields["minimum"],
                                       targetFields["maximum"]])
                curProvider.addFeatures([feature])

            self.finalizeLayers(allNewLayers, targetField, newGroupNode, self.paramLimits, addLegend = self.addLegend)
            self.newLayers.update(allNewLayers)
        QMessageBox.information(self.iface.mainWindow(),
            "Finished creating requested maps.",
            "The following maps have been generated: \n\n- " + "\n- ".join(newlyGeneratedMaps))
        
    def postProcessModelData(self, paramInfo={}, parameterOrder=[]):
        super(AKFeatureResultsMap, self).postProcessModelData(paramInfo, parameterOrder)
    
    def getTargetIndex(self, targetField):
        targetIndices = {"earliest":2,
                         "latest":3,
                         "mean":4,
                         "minimum":5,
                         "maximum":6}
        targetIndex = targetIndices[targetField]
        return targetIndex
        
    def getTargetField(self):
        targetField = ""
        targetFieldValues = {self.mapSettingsForm.rdEarliest : "earliest",
                             self.mapSettingsForm.rdLatest : "latest",
                             self.mapSettingsForm.rdAverage: "mean",
                             self.mapSettingsForm.rdMinimum: "minimum", 
                             self.mapSettingsForm.rdMaximum: "maximum"}
        for curRadioButton in targetFieldValues:
            if curRadioButton.isChecked():
                targetField = targetFieldValues[curRadioButton]
        return targetField