#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 import QtGui
from PyQt4.Qt import QMessageBox
from PyQt4.QtGui import QColor
import os

from AKFeatureResultsPlot import AKFeatureResultsPlot
from form.AKWidgetStiffPlotSettings import AKWidgetStiffPlotSettings
from external.chemPlotLib.StiffPlot import StiffPlot, STIFFSETTINGS

class AKFeatureResultsStiff(AKFeatureResultsPlot):
    '''
    This feature provides the functionality for the second form to create stiff plots. 
    '''
    def __init__(self, settings, iface, parent=None):
        super(AKFeatureResultsStiff, self).__init__(settings, iface, StiffPlot, windowTitle = "Stiff Results", parent=parent)
        self.m_form.plotButton.setText("Save Plots")
        self.distY = 0.0
        self.scaleX = 1.0
        self.scaleY = 1.0
        
    def customizeForm(self):
        super(AKFeatureResultsStiff, self).customizeForm()
        self.stiffSettingsForm = AKWidgetStiffPlotSettings(self.iface, self.m_form)    
        self.m_form.customResultsGroup.layout().addWidget(self.stiffSettingsForm)
        
        mod = self.plotSettingsModel 
        polygon_color_id =  mod.columnFromField(STIFFSETTINGS.stiff, STIFFSETTINGS.polygon_color_id)
        showLabels_id =  mod.columnFromField(STIFFSETTINGS.stiff, STIFFSETTINGS.showLabels_id)
        showVerticalLine_id =  mod.columnFromField(STIFFSETTINGS.stiff, STIFFSETTINGS.showVerticalLine_id)
        showHorizontalLines_id =  mod.columnFromField(STIFFSETTINGS.stiff, STIFFSETTINGS.showHorizontalLines_id)
        showHorizontalAxe_id =  mod.columnFromField(STIFFSETTINGS.stiff, STIFFSETTINGS.showHorizontalAxe_id)
        fontSize_id =  mod.columnFromField(STIFFSETTINGS.stiff, STIFFSETTINGS.fontSize_id)        
        xRange_id =  mod.columnFromField(STIFFSETTINGS.stiff, STIFFSETTINGS.xRange_id)
        yLength_id =  mod.columnFromField(STIFFSETTINGS.stiff, STIFFSETTINGS.yLength_id)
         
        self.mapper.addMapping(self.stiffSettingsForm.polygon_color, polygon_color_id) ;
        self.mapper.addMapping(self.stiffSettingsForm.showLabels, showLabels_id)
        self.mapper.addMapping(self.stiffSettingsForm.showVerticalLine, showVerticalLine_id)
        self.mapper.addMapping(self.stiffSettingsForm.showHorizontalLines, showHorizontalLines_id)
        self.mapper.addMapping(self.stiffSettingsForm.showHorizontalAxe, showHorizontalAxe_id)
        self.mapper.addMapping(self.stiffSettingsForm.fontSize, fontSize_id)
        
        self.mapper.addMapping(self.stiffSettingsForm.xRange, xRange_id)
        self.mapper.addMapping(self.stiffSettingsForm.yLength, yLength_id)         

        self.mapper.toFirst()
        
        self.stiffSettingsForm.polygon_font_color_picker.setConnections(self.plotSettingsModel, self.stiffSettingsForm.polygon_color, polygon_color_id)
        self.stiffSettingsForm.polygon_font_color_picker.setColor(QColor(self.stiffSettingsForm.polygon_color.text()))
        self.stiffSettingsForm.polygon_color.hide()
               
        # disable unused things
        self.plotSettingsForm.title_label.setEnabled(False)
        self.plotSettingsForm.markerGroup.hide()
        self.plotSettingsForm.lineGroup.hide()
        self.plotSettingsForm.legendGroup.hide()
    
    def initialize(self):
        self.showData(hideMeasurements=True)
        super(AKFeatureResultsStiff, self).initialize()
        
    def onActionClicked(self):
        directory = QtGui.QFileDialog.getExistingDirectory(parent=self.m_form, caption="Select directory where to save Stiff plots")
        if directory == "":
            return
        model = self.sampleMeasurementsModel
        values = {}
        numOfSamples = model.rowCount()
        for row in range(numOfSamples):
            isValid = model.data(self.sampleMeasurementsModel.index(row, model.COLUMNS["valid"]))
            if(isValid):
                sample = model.data(model.index(row, model.COLUMNS["Sample"]))
                dict = {}
                paramId = self.paramInfo["N209MQL"]["id"]
                dict["Ca"] = model.data(model.index(row, model.COLUMNS[paramId]))                            
                paramId = self.paramInfo["N168MQL"]["id"]
                dict["HCO3"] = model.data(model.index(row, model.COLUMNS[paramId])) 
                paramId = self.paramInfo["N582MQL"]["id"]
                dict["SO4"] = model.data(model.index(row, model.COLUMNS[paramId])) 
                paramId = self.paramInfo["N247MQL"]["id"]
                dict["Cl"] = model.data(model.index(row, model.COLUMNS[paramId])) 
                paramId = self.paramInfo["N580MQL"]["id"]
                dict["Na"] = model.data(model.index(row, model.COLUMNS[paramId])) 
                paramId = self.paramInfo["N436MQL"]["id"]
                dict["Mg"] = model.data(model.index(row, model.COLUMNS[paramId]))
                values[sample] = dict
        
        generateFiles = []
        format_file ="svg"
        for sample in values:
            myChart = StiffPlot(self.iface.mainWindow())
            myChart.setData(sample, values[sample])
            fileName = sample + "." + format_file
            filePathName = os.path.join(directory, fileName)
            myChart.set_settings(self.plotSettingsModel.getDictData())
            myChart.save(filePathName, format_file)
            myChart.remove()
            generateFiles.append(filePathName)
        
        QMessageBox.information(self.iface.mainWindow(),
                        "All plot images are saved to files.",
                        "The following files have been generated: \n- " + "\n- ".join(generateFiles))

    def postProcessModelData(self, paramInfo, parameterOrder):
        super(AKFeatureResultsStiff, self).postProcessModelData(paramInfo, parameterOrder)
        self.addValidColumn(paramInfo, parameterOrder)