#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 QColor

from form.AKWidgetPiperPlotSettings import AKWidgetPiperPlotSettings
from external.chemPlotLib.PiperPlot import PiperPlot, PIPERSETTINGS
from AKFeatureResultsPlot import AKFeatureResultsPlot

class AKFeatureResultsPiper(AKFeatureResultsPlot):
    '''
    This feature provides the functionality for the second form to create piper plots. 
    '''
    def __init__(self, settings, iface, parent=None):
        super(AKFeatureResultsPiper, self).__init__(settings, iface, PiperPlot, windowTitle = "Piper Results", parent=parent)
        
    def customizeForm(self):
        super(AKFeatureResultsPiper, self).customizeForm()        
        self.piperSettingsForm = AKWidgetPiperPlotSettings(self.iface, self.m_form)    
        self.m_form.customResultsGroup.layout().addWidget(self.piperSettingsForm)
                
        mod = self.plotSettingsModel
         
        pane_separation_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.pane_separation_id)
        pane_surface_color_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.pane_surface_color_id)
        
        pane_border_color_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.pane_border_color_id)
        
        grid_divisions_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.grid_divisions_id)
        grid_line_style_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.grid_line_style_id)
        grid_line_color_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.grid_line_color_id)
        grid_line_thickness_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.grid_line_thickness_id)
        
        subgrid_divisions_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.subgrid_divisions_id)
        subgrid_line_style_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.subgrid_line_style_id)
        subgrid_line_color_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.subgrid_line_color_id)
        subgrid_line_thickness_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.subgrid_line_thickness_id)
        
        font_axes_labels_size_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.font_axes_labels_size_id)
        font_corners_labels_size_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.font_corners_labels_size_id)
        font_grid_labels_size_id =  mod.columnFromField(PIPERSETTINGS.piper, PIPERSETTINGS.font_grid_labels_size_id)                
                 
        self.mapper.addMapping(self.piperSettingsForm.font_axes_labels_size, font_axes_labels_size_id)
        self.mapper.addMapping(self.piperSettingsForm.font_corners_labels_size, font_corners_labels_size_id)
        self.mapper.addMapping(self.piperSettingsForm.font_grid_labels_size, font_grid_labels_size_id)
        
        self.mapper.addMapping(self.piperSettingsForm.pane_separation, pane_separation_id)
        self.mapper.addMapping(self.piperSettingsForm.pane_surface_color, pane_surface_color_id)
        self.mapper.addMapping(self.piperSettingsForm.pane_border_color, pane_border_color_id)
        
        self.mapper.addMapping(self.piperSettingsForm.grid_divisions, grid_divisions_id)
        self.mapper.addMapping(self.piperSettingsForm.grid_line_style, grid_line_style_id)
        self.mapper.addMapping(self.piperSettingsForm.grid_line_color, grid_line_color_id)
        self.mapper.addMapping(self.piperSettingsForm.grid_line_thickness, grid_line_thickness_id)
        
        self.mapper.addMapping(self.piperSettingsForm.subgrid_divisions, subgrid_divisions_id)
        self.mapper.addMapping(self.piperSettingsForm.subgrid_line_style, subgrid_line_style_id)
        self.mapper.addMapping(self.piperSettingsForm.subgrid_line_color, subgrid_line_color_id)
        self.mapper.addMapping(self.piperSettingsForm.subgrid_line_thickness, subgrid_line_thickness_id)        
        
        self.mapper.toFirst()
                         
        currentText = mod.data(mod.index(0,grid_line_style_id))
        comboW = self.piperSettingsForm.grid_line_style
        comboW.setCurrentIndex(comboW.findText(currentText))
        
        currentText = mod.data(mod.index(0,subgrid_line_style_id))
        comboW = self.piperSettingsForm.subgrid_line_style
        comboW.setCurrentIndex(comboW.findText(currentText)) 
        
        self.piperSettingsForm.pane_surface_color_picker.setConnections(self.plotSettingsModel, self.piperSettingsForm.pane_surface_color, pane_surface_color_id)
        self.piperSettingsForm.pane_surface_color_picker.setColor(QColor(self.piperSettingsForm.pane_surface_color.text()))
        self.piperSettingsForm.pane_surface_color.hide()
        
        self.piperSettingsForm.pane_border_color_picker.setConnections(self.plotSettingsModel, self.piperSettingsForm.pane_border_color, pane_border_color_id)
        self.piperSettingsForm.pane_border_color_picker.setColor(QColor(self.piperSettingsForm.pane_border_color.text()))
        self.piperSettingsForm.pane_border_color.hide()
        
        self.piperSettingsForm.grid_line_color_picker.setConnections(self.plotSettingsModel, self.piperSettingsForm.grid_line_color, grid_line_color_id)
        self.piperSettingsForm.grid_line_color_picker.setColor(QColor(self.piperSettingsForm.grid_line_color.text()))
        self.piperSettingsForm.grid_line_color.hide()
        
        self.piperSettingsForm.subgrid_line_color_picker.setConnections(self.plotSettingsModel, self.piperSettingsForm.subgrid_line_color, subgrid_line_color_id)
        self.piperSettingsForm.subgrid_line_color_picker.setColor(QColor(self.piperSettingsForm.subgrid_line_color.text()))
        self.piperSettingsForm.subgrid_line_color.hide()             
        
    
    def initialize(self):
        self.showData(hideMeasurements=True)
        super(AKFeatureResultsPiper, self).initialize()
        
    def onActionClicked(self):
        model = self.sampleMeasurementsModel
        myChart = PiperPlot(self.m_form)
        
        labels = []    
        Ca = []
        Mg = []
        NaK = []
        HCO3CO3 = []    
        SO4 = []
        Cl = []
        numOfSamples = self.sampleMeasurementsModel.rowCount()
        for row in range(numOfSamples):
            isValid = model.data(self.sampleMeasurementsModel.index(row, model.COLUMNS["valid"]))
            if(isValid):
                label = model.data(model.index(row, model.COLUMNS["Sample"]))
                labels.append(label)
                value = model.data(model.index(row, model.COLUMNS["Ca %"]))
                Ca.append(value)
                value = model.data(model.index(row, model.COLUMNS["Mg %"]))
                Mg.append(value)
                value = model.data(model.index(row, model.COLUMNS["Na + K %"]))
                NaK.append(value)
                value = model.data(model.index(row, model.COLUMNS["HCO3 + CO3 %"]))
                HCO3CO3.append(value)
                value = model.data(model.index(row, model.COLUMNS["SO4 %"]))
                SO4.append(value)
                value = model.data(model.index(row, model.COLUMNS["Cl %"]))
                Cl.append(value)
        values = {'Ca':Ca, 'Mg':Mg, 'NaK':NaK, 'HCO3CO3':HCO3CO3, 'SO4':SO4, 'Cl':Cl}   
        myChart.setData(labels, values)
        myChart.set_settings(self.plotSettingsModel.getDictData())
        myChart.draw()

    def postProcessModelData(self, paramInfo, parameterOrder):
        super(AKFeatureResultsPiper, self).postProcessModelData(paramInfo, parameterOrder)
        model = self.sampleMeasurementsModel
        
        self.paramInfo = paramInfo
        
        model.addSimpleColumn("Ca %")
        model.addSimpleColumn("Mg %")
        model.addSimpleColumn("Na + K %")
        model.addSimpleColumn("HCO3 + CO3 %")
        model.addSimpleColumn("SO4 %")
        model.addSimpleColumn("Cl %")
        self.addValidColumn(paramInfo, parameterOrder)
        
        numOfSamples = model.rowCount()
        for row in range(numOfSamples):
            isValid = model.data(model.index(row, model.COLUMNS["valid"]))
            if(isValid):
                paramId = paramInfo["N209MQL"]["id"]
                Ca = model.data(model.index(row, model.COLUMNS[paramId]))
                paramId = paramInfo["N436MQL"]["id"]
                Mg = model.data(model.index(row, model.COLUMNS[paramId]))
                paramId = paramInfo["N580MQL"]["id"]
                Na = model.data(model.index(row, model.COLUMNS[paramId]))
                paramId = paramInfo["N247MQL"]["id"]
                Cl = model.data(model.index(row, model.COLUMNS[paramId]))
                paramId = paramInfo["N582MQL"]["id"]
                SO4 = model.data(model.index(row, model.COLUMNS[paramId]))
                paramId = paramInfo["N168MQL"]["id"]
                HCO3 = model.data(model.index(row, model.COLUMNS[paramId]))
                paramId = paramInfo["N553MQL"]["id"]
                K = model.data(model.index(row, model.COLUMNS[paramId]))

                totalCations = Ca + Mg + Na + K
                totalAnions = Cl + SO4 + HCO3

                Ca_per = Ca / totalCations * 100
                Mg_per = Mg / totalCations * 100
                NaK_per = (Na + K) / totalCations * 100
                HCO3CO3_per =( HCO3 ) / totalAnions * 100
                SO4_per = SO4 / totalAnions * 100
                Cl_per = Cl / totalAnions * 100

                model.setData(model.index(row, model.COLUMNS["Ca %"]), Ca_per)
                model.setData(model.index(row, model.COLUMNS["Mg %"]), Mg_per)
                model.setData(model.index(row, model.COLUMNS["Na + K %"]), NaK_per)
                model.setData(model.index(row, model.COLUMNS["HCO3 + CO3 %"]), HCO3CO3_per)
                model.setData(model.index(row, model.COLUMNS["SO4 %"]), SO4_per)
                model.setData(model.index(row, model.COLUMNS["Cl %"]), Cl_per)