#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
from collections import OrderedDict
import copy, os

from AKFeatureResults import AKFeatureResults

class AKFeatureResultsStatQuimet(AKFeatureResults):
    '''
    This feature provides the functionality for the second form to export data for StatQuimet. 
    '''
    def __init__(self, settings, iface, parent=None):
        super(AKFeatureResultsStatQuimet, self).__init__(settings, iface, windowTitle = "StatQuimet Results", parent=parent)

    def customizeForm(self):        
        super(AKFeatureResultsStatQuimet, self).customizeForm()        
        self.m_form.plotButton.setText("Export data")  
                
    def initialize(self):
        self.showData()
        super(AKFeatureResultsStatQuimet, self).initialize()
        
    def onActionClicked(self):
        directory = QtGui.QFileDialog.getExistingDirectory(parent=self.m_form, caption="Select directory where to save StatQuimet input excel")
        if directory == "":
            return
        
        model = self.sampleMeasurementsModel
        timeSeriesData = self.storeDataInTimeSeries()
        dataExcel, dataWExcel, header = self.writeStatQuimetExcel(model, timeSeriesData)
        
        allData = copy.deepcopy(header)
        nameFile1 = "data.xls"
        fileName = os.path.join(directory, nameFile1)
        content = pyexcel.utils.dict_to_array(dataExcel)
        allData.extend(content)
        sheet = pyexcel.Sheet(allData, name="Data")
        sheet.save_as(fileName)
        
        allData = copy.deepcopy(header)
        nameFile2 = "data_w.xls"
        fileName = os.path.join(directory, nameFile2)
        content = pyexcel.utils.dict_to_array(dataWExcel)
        allData.extend(content)
        sheet = pyexcel.Sheet(allData, name="Data")
        sheet.save_as(fileName)
        
        QtGui.QMessageBox.information(self.iface.mainWindow(),
            "Finished creating requested export.",
            "The following files have been generated: \n\n- " + "\n- ".join([nameFile1, nameFile2]))

    def postProcessModelData(self, paramInfo, parameterOrder):
        super(AKFeatureResultsStatQuimet, self).postProcessModelData({}, [])
        self.showData()

    def writeStatQuimetExcel(self, model, timeSeriesData):
        # Start the table, and describe the columns        
        basicFields =["Point", "Date", "Campaign", "Sample", "Coordinate X", "Coordinate Y"]
        ## Headers...
        dataExcel = OrderedDict()
        dataWExcel = OrderedDict()
        
        for curParam in basicFields:
            dataExcel[curParam] = []
            dataWExcel[curParam] = []
            
        paramIds = {}
        for units in timeSeriesData:
            unitsName =  timeSeriesData[units]["valuesLabel"]
            for serie in timeSeriesData[units]["series"]:
                parameterName = timeSeriesData[units]["series"][serie]["parameterName"]
                parameterId = timeSeriesData[units]["series"][serie]["parameterId"]
                value = parameterName + " (" + unitsName + ")"
                
                if not parameterId in paramIds:
                    dataExcel[value] = []
                    dataWExcel[value] = []
                    
                    paramIds[parameterId] = value

        numChemOfParams = len(paramIds)
        numFixedParams = len(basicFields)
        totalColumns = numChemOfParams + numFixedParams
        
        numOfSamples = model.rowCount()
        for row in range(numOfSamples):
            
            rowValues = {}
            for curParam in basicFields:
                value = model.data(model.index(row, model.COLUMNS[curParam]))                
                rowValues[curParam] = value

            completeRow = True            
            for parameterId in paramIds:                
                value = model.data(model.index(row, model.COLUMNS[parameterId]))
                
                if value == None:
                    completeRow = False
                    value = "w"                    
                rowValues[paramIds[parameterId]] = value
            
            dictToFill = dataExcel
            
            if  not completeRow:
                dictToFill = dataWExcel

            for field in rowValues:                
                dictToFill[field].append(rowValues[field]) 

        emptyRow =  [None]*totalColumns        
        headers = [emptyRow, emptyRow, emptyRow]
        fourthRow =  [None]*totalColumns
        for i in range(len(paramIds)):
            pos = i+numFixedParams
            fourthRow[pos] = i+1
        
        headers.append(fourthRow)             

        return dataExcel, dataWExcel, headers