#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 QTableWidgetItem, QCheckBox, QHBoxLayout, QWidget,QFileDialog
from PyQt4.QtCore import Qt
from PyQt4 import QtGui
from collections import OrderedDict
import os, copy
from external import pyexcel

from AKFeatureResults import AKFeatureResults
from form.AKWidgetExportMixSettings import AKWidgetExportMixSettings

class AKFeatureResultsExcelMix(AKFeatureResults):
    '''
    This feature provides the functionality for the second Mix Export form. 
    '''
    def __init__(self, settings, iface, parent=None):
        super(AKFeatureResultsExcelMix, self).__init__(settings, iface, windowTitle = "ExcelMix Results", parent=parent)
                
    def customizeForm(self):
        super(AKFeatureResultsExcelMix, self).customizeForm()        
        self.mixSettingsForm = AKWidgetExportMixSettings(self.iface, self.m_form)  
        self.m_form.customResultsGroup.show()
        self.m_form.customResultsGroup.setTitle("Mix settings")
        self.m_form.customResultsGroup.layout().addWidget(self.mixSettingsForm)
        self.m_form.plotButton.setText("Export data")   
        
    def initialize(self):
        self.showData()
        super(AKFeatureResultsExcelMix, self).initialize()
        
    def onActionClicked(self):
        files_types = "LibreOffice (*.ods);;Excel (*.xls);;CSV (*.csv)"
        fileName = QFileDialog.getSaveFileName(self.m_form, "Save report", os.getenv("HOME"), files_types)
        if fileName == "":
            return
        
        model = self.sampleMeasurementsModel
        timeSeriesData = self.storeDataInTimeSeries()
        dataExcel_all, dataExcel_samples,  dataExcel_endMembers = self.writeMixExcel(model, timeSeriesData)
        dataExcel_all_table = pyexcel.utils.dict_to_array(dataExcel_all)
        dataExcel_samples_table = pyexcel.utils.dict_to_array(dataExcel_samples)
        dataExcel_endMembers_table = pyexcel.utils.dict_to_array(dataExcel_endMembers)  
        
        all_Excel = {"Mix Info": dataExcel_all_table,
                     "Mix Samples": dataExcel_samples_table,
                     "Mix EndMembers": dataExcel_endMembers_table}
                        
        book = pyexcel.Book(all_Excel)        
        book.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 postProcessModelData(self, paramInfo, parameterOrder):
        super(AKFeatureResultsExcelMix, self).postProcessModelData({}, [])
        self.showData()
        self.fillMixWidget()
                
    def fillMixWidget(self):
        model = self.sampleMeasurementsModel
        tableWidget = self.mixSettingsForm.tw
        tableWidget.setColumnCount(4) 
        tableWidget.setHorizontalHeaderLabels(["SampleRow", "Active", "Sample name", "Is End Member"])
        tableWidget.setColumnHidden(0, True)
        
        numOfSamples = model.rowCount()
        for curSample in range(numOfSamples):
            
            sampleName = model.data(model.index(curSample, model.COLUMNS["Sample"]))
            sampleRow = curSample

            row = tableWidget.rowCount()
            tableWidget.insertRow(row)
            
            newItem = QTableWidgetItem(sampleRow)
            tableWidget.setItem(row, 0, newItem) 
            
            newItem = QCheckBox(tableWidget)            
            
            pWidget = QWidget();
            pLayout = QHBoxLayout(pWidget);
            pLayout.addWidget(newItem);
            pLayout.setAlignment(Qt.AlignCenter);
            pLayout.setContentsMargins(0,0,0,0);
            pWidget.setLayout(pLayout);
            
            newItem.setChecked(True)
            tableWidget.setCellWidget(row, 1, pWidget)            
            
            newItem = QTableWidgetItem(sampleName)
            newItem.setTextAlignment(Qt.AlignCenter);
            tableWidget.setItem(row, 2, newItem)            
             
            newItem = QCheckBox(tableWidget)
            pWidget = QWidget();
            pLayout = QHBoxLayout(pWidget);
            pLayout.addWidget(newItem);
            pLayout.setAlignment(Qt.AlignCenter);
            pLayout.setContentsMargins(0,0,0,0);
            pWidget.setLayout(pLayout);
            
            tableWidget.setCellWidget(row, 3, pWidget)   
        
        tableWidget.resizeColumnsToContents();
        tableWidget.horizontalHeader().setStretchLastSection(True);
        
    def writeMixExcel(self, model, timeSeriesData):
#         timePlotData = {unitId: {"valuesLabel": "mg/L",
#                                  "unitCode": "MGL",
#                                  "datesLabel": "time",
#                                  "title": "MyTitle_1",
#                                  "parameterIds": [parId1,parId2],
#                                  "series" : {"pointId_parId" : {"dates": ["23011977",  "25011977"],
#                                                                  "values": [1.5, 0.5],
#                                                                   "samples": ["asdfs", "asdfsdfff"],
#                                                                   "parameterName": "Magnesium",
#                                                                   "parameterId": 23,
#                                                                   "point" : "P12",
#                                                                   "pointId" : 123
#                                                                   },
#                                                "pointId_parId" : {"dates": ["23011977",  "25011977"],
#                                                                    "values": [1.5, 0.5],
#                                                                    "samples": ["asdfs", "asdfsdfff"],
#                                                                    "parameterName": "Chloride",
#                                                                    "parameterId": 23,
#                                                                    "point" : "P12",
#                                                                    "pointId" : 123
#                                                                    } 
#                                                }
#                                        },....  
#                             }
        ## Headers...
        basicFields =["Point", "Date", "Campaign", "Sample", "Coordinate X", "Coordinate Y"]        
        dataExcel_all = OrderedDict()
        dataExcel_samples = OrderedDict()
        dataExcel_samples["Sample"] = []
        
        for curParam in basicFields:
            dataExcel_all[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_all[value] = []
                    dataExcel_samples[value] = []                    
                    paramIds[parameterId] = value

        dataExcel_all["Is End Member"] = []
        dataExcel_endMembers = copy.deepcopy(dataExcel_samples)
        tableWidget = self.mixSettingsForm.tw
        numOfSamples = tableWidget.rowCount()       
        for row in range(numOfSamples):
            #active = tableWidget.item(row, 1).takeAt(0).checkState() == Qt.Checked
            #.data(Qt.DisplayRole)
            active = tableWidget.cellWidget(row, 1).layout().itemAt(0).widget().isChecked()
            if active:
                rowValues = {}
                
                isEndMember = tableWidget.cellWidget(row, 3).layout().itemAt(0).widget().isChecked()
                rowValues["Is End Member"] = isEndMember
                
                value = model.data(model.index(row, model.COLUMNS["Sample"]))                                
                if not isEndMember:
                    dataExcel_samples["Sample"].append(value)
                else:
                    dataExcel_endMembers["Sample"].append(value)
                        
                
                for curParam in basicFields:
                    value = model.data(model.index(row, model.COLUMNS[curParam]))                
                    rowValues[curParam] = value                    
              
                for parameterId in paramIds:                
                    value = model.data(model.index(row, model.COLUMNS[parameterId])) 
                    rowValues[paramIds[parameterId]] = value
                    if not isEndMember:
                        dataExcel_samples[paramIds[parameterId]].append(value)
                    else:
                        dataExcel_endMembers[paramIds[parameterId]].append(value)                    
                
                for field in rowValues:
                    dataExcel_all[field].append(rowValues[field])
        return dataExcel_all, dataExcel_samples, dataExcel_endMembers