#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 external import pyexcel
import os

from AKFeatureResultsIonicBalance import AKFeatureResultsIonicBalance

class AKFeatureResultsEasyQuim(AKFeatureResultsIonicBalance):
    '''
    This feature provides the functionality for the second EasyQuim Export form. 
    '''
    def __init__(self, settings, iface, parent=None):
        super(AKFeatureResultsEasyQuim, self).__init__(settings, iface, windowTitle="EasyQuim Export Results", parent=parent)

    def customizeForm(self):        
        super(AKFeatureResultsEasyQuim, self).customizeForm()        
        self.m_form.plotButton.setText("Export data")  
    
    def onActionClicked(self):
        files_types = "LibreOffice (*.ods);;Excel (*.xls);;CSV (*.csv)"
        fileName = QtGui.QFileDialog.getSaveFileName(self.m_form, "Save report", os.getenv("HOME"), files_types)
        if fileName == "":
            return
        
        model = self.sampleMeasurementsModel
        table = self.writeEasyQuimReport(model)
        
        sheet = pyexcel.Sheet(table, name="Easy Quim")
        sheet.save_as(fileName)        
        
        QtGui.QMessageBox.information(self.iface.mainWindow(),
            "Finished creating requested export.",
            "The following files have been generated: \n\n- " + "\n- ".join([fileName]))
        
    def writeEasyQuimReport(self, model):        
        # Start the table, and describe the columns
        paramList = {"N209MQL":"Ca","N247MQL":"Cl" ,"N436MQL":"Mg" ,"N580MQL":"Na","N582MQL":"SO4","N168MQL":"HCO3",
                     "N553MQL":"K","N592MQL":"TAC","N480MQL":"NO3","N216USC":"CE","N540UNK":"pH","N326UNK":"DUR",
                     "N647UNK":"TSD","N124MQL":"NH4", "N595GCG":"Temperature"}
        
        cations = ["N580MQL", "N553MQL", "N209MQL", "N436MQL", "N124MQL"]
        anions = ["N168MQL", "N582MQL", "N247MQL" , "N480MQL"]
        generalParams = ["N216USC", "N595GCG", "N540UNK", "N592MQL", "N326UNK", "N647UNK"]
        generalParamsUnits = {"TAC":"(mgl)", "CE":"(uscm3)", "pH":"", "DUR": "(mgl)", "TSD":"", "Temperature":"(degC)"}        
        basicFields =[ "Date", "Sample", "Coordinate X", "Coordinate Y"]
        
        dataOrder = ["basicFields", "generalParams", "anions_mgl", "cations_mgl"]
        data = {}        
        data["basicFields"]= {"title":'QGis Fields', "values":{},"param":basicFields, "nameFromParamList":False, "specificUnits": False, "units":""}
        data["generalParams"]= {"title":'General parameters',"values":{}, "param":generalParams, "nameFromParamList":True, "specificUnits": True, "units":generalParamsUnits}
        data["cations_mgl"]= {"title":'Cations in mg/l',"values":{}, "param":cations, "nameFromParamList":True,"specificUnits": False, "units":"(mgl)"}
        data["anions_mgl"]= {"title":'Anions in mg/l',"values":{}, "param":anions,"nameFromParamList":True,"specificUnits": False, "units":"(mgl)"}
        data["cations_meq"]= {"title":'Cations in meq/l',"values":{}, "param":cations, "nameFromParamList":True,"specificUnits": False, "units":"(meql)"}
        data["anions_meq"]= {"title":'Anions in meq/l',"values":{}, "param":anions, "nameFromParamList":True,"specificUnits": False, "units":"(meql)"}
        data["cations_mgl_percentage"]= {"title":'Cations Weight Percentage',"values":{}, "param":cations, "nameFromParamList":True,"specificUnits": False, "units":"(mgl %)"}
        data["anions_mgl_percentage"]= {"title":'Anions Weight Percentage',"values":{}, "param":anions,"nameFromParamList":True,"specificUnits": False, "units":"(mgl %)"}
        data["cations_meq_percentage"]= {"title":'Cations meq Percentage',"values":{}, "param":cations, "nameFromParamList":True,"specificUnits": False, "units":"(meql %)"}
        data["anions_meq_percentage"]= {"title":'Anions  meq Percentage',"values":{}, "param":anions, "nameFromParamList":True,"specificUnits": False, "units":"(meql %)"}
        data["ionic_balance"]= {"title":'IonicBalance',"values":{}, "param":["ionicBalance"], "nameFromParamList":False,"specificUnits": False, "units":""}      
    
        self.loadData(model, dataOrder, data)
        numOfSamples = len(data["basicFields"]["values"]["Sample"])
                
        table = []
        allRows = {}
        cations.append("sum.cations")
        anions.append("sum.anions")
        paramList["sum.cations"] = "Sum of Cations"
        paramList["sum.anions"] = "Sum of Anions" 
        for group in dataOrder:
            params = data[group]["param"]
            groupDict = {}
            allRows[group] = groupDict
            for param in params:
                if param != "N124MQL":
                    tr = []
                    table.append(tr)
                    allRows[group][param] = tr
            #empty row after groups
            if group in ["basicFields"]:
                tr = []
                table.append(tr)
            elif group in ["generalParams"]:
                tr = []
                table.append(tr)
                tr = []
                table.append(tr)
                tr = []
                table.append(tr)
                tr = []
                table.append(tr)
            elif group in ["cations_mgl"]:          
                tr = []
                table.append(tr)
            elif group in ["anions_mgl"]:
                tr = []
                table.append(tr)                
                                
            
        tr = []
        table.append(tr)
        allRows["cations_mgl"]["N124MQL"] = tr

        #headers
        for group in dataOrder:
            params = data[group]["param"]
            for curParam in params:
                tr = allRows[group][curParam]
                val = curParam
                if data[group]["nameFromParamList"]:
                    val = paramList[curParam]
                tr.append(val)

        for col in range(numOfSamples):
            for group in dataOrder:
                if group in ["basicFields", "generalParams"]:                
                    params = data[group]["param"]
    
                    for curParam in params:
                        tr = allRows[group][curParam]
                        val =  data[group]["values"][curParam][col]
                        tr.append(val)
                
                elif group in ["cations_mgl", "anions_mgl", "cations_meq", "anions_meq"]:
                    params = data[group]["param"]
                    sum = 0
                    for curParam in params:
                        if curParam not in ["sum.cations", "sum.anions"]:
                            tr = allRows[group][curParam]
                            val =  data[group]["values"][curParam][col]
                            tr.append(val)   
                            if val != None:
                                sum +=val
                        else:
                            tr = allRows[group][curParam]                            
                            tr.append(sum)   
     
        return table