#!/usr/bin/env python

"""
This file is part of open-ihm.

open-ihm 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 3 of the License, or (at your
option) any later version.

open-ihm is distributed in the hope that it will be useful, but
WITHOUT 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 open-ihm.  If not, see <http://www.gnu.org/licenses/>.
"""

# imports from PyQt4 package
from PyQt4.QtCore import *
from PyQt4.QtGui import *

import includes.mysql.connector as connector
from data.config import Config
from data.report_settingsmanager import ReportsSettingsManager
    
class TableViewMixin(object):

    def countRowsSelected(self, tblVw):
         selectedRows = self.getSelectedRows(tblVw)
         return len(selectedRows)

    def getSelectedRows(self, tblVw):
         selectedRows = []
         selectedIndexes = tblVw.selectedIndexes()

         for indexVal in selectedIndexes:
             if indexVal.row() not in selectedRows:
                 selectedRows.append(indexVal.row())

         return selectedRows

    def getCurrentRow(self, tblVw):
         indexVal = tblVw.currentIndex()
         return indexVal.row()
    
    def getSelectedCharsList(self,selectedIndexes,tblVw):
        ''' get list of user selected household characteristics as part of the criteria for report generation'''
		
	selectedHChars = []
	#selectedIndexes = tblVw.selectedIndexes()
		
	for indexVal in selectedIndexes:
            currentitem = tblVw.model().item(indexVal.row(),0).text()
	    if currentitem not in selectedHChars:
		selectedHChars.append(str(currentitem))
	return selectedHChars

    def getSelectedAssetList(self,selectedIndexes,tblVw):
        ''' get list of user selected project assets as part of the criteria for report generation'''
		
	selectedassets = []
	#selectedIndexes = tblVw.selectedIndexes()
		
	for indexVal in selectedIndexes:
            templist = []
            currentcategory = tblVw.model().item(indexVal.row(),0).text()
            currentassetname = tblVw.model().item(indexVal.row(),1).text()
            templist.extend([str(currentcategory),str(currentassetname)])
            templist = tuple(templist)
	    if templist not in selectedassets:
		selectedassets.append(templist)
	return selectedassets

    def displayHouseholdNames(self, hholdnames):
        ''' Insert household names for the selected Project'''

        #hholdnames = self.getHouseholdNames()
        model = QStandardItemModel()
        parent = QModelIndex()
        name = 'All Households'
        numberofrows = len(hholdnames)

        model.insertRow(0,parent )
        model.insertColumn(0, parent ) #one column for children
        parent = model.index( 0, 0 )
        model.setData( parent, name )

        #Insert project-specific household names as childred of the node 'All Households'
        parent = model.index(0, 0, QModelIndex())
        model.insertColumn(0, parent )
        model.insertRows( 0, numberofrows, parent )
        num = 0
        for hholdname in hholdnames:
            child = model.index( num, 0, parent )
            model.setData(child, hholdname[0])
            num = num + 1
                        		
        model.setHorizontalHeaderItem(0,QStandardItem('Select Household Names'))
        self.treeViewHouseholds.setModel(model)
        self.treeViewHouseholds.show()

    def setHouseholdCharsModel(self,hholdchars):
        
        ''' get household characteristics relevant to selected project'''
        model = QStandardItemModel()
        model.setHorizontalHeaderItem(0,QStandardItem('Select Household Names'))
	num = 0

        for hholdchar in hholdchars:
            
            qtHCharacteristic = QStandardItem( "%s" % hholdchar)
            model.setItem( num, 0, qtHCharacteristic )
            num = num + 1
        return model
    
    def setAssetsModel(self,assets):
        ''' Retrieve and display available assets ''' 
        
        model = QStandardItemModel(1,2)
        
        # add  data rows
        num = 0
        for asset in assets:
            qtAssetType = QStandardItem( "%s" % asset[0] )
            qtCategory = QStandardItem( "%s" % asset[1] )
            model.setItem( num, 0, qtAssetType )
            model.setItem( num, 1, qtCategory )
            num = num + 1

        # set model headers
        model.setHorizontalHeaderItem(0,QStandardItem('Asset Category'))
        model.setHorizontalHeaderItem(1,QStandardItem('Asset Name'))
        
        return model

    def getHouseholdsSelection(self,projectid,selectedIndexes,treeVw):
        '''Get names of households selected by the user for charting'''
        
        parentIndex = treeVw.model().index(0, 0, QModelIndex())
        hholdnames = []
        
        if len(selectedIndexes) != 0:
            if parentIndex in selectedIndexes:
                connector = ReportsSettingsManager()
                houses = connector.getProjectHouseholds(projectid)
                for house in houses:
                    hholdnames.append(str(house[0]))
            else:
                for indexVal in selectedIndexes:
                    currentitem = treeVw.model().data(indexVal, Qt.DisplayRole).toString()
                    hholdnames.append(str(currentitem))
        else:
            QMessageBox.information(self,"Households By Income Source","No Households Selected")
        return hholdnames


class MDIDialogMixin(object):
    """Used by all dialog boxes.
    """

    def setMdi(self, mdi):
        self.mdi = mdi
        
    def mdiClose(self):
        """Close this dialog box.
        
        The dialog may be the active sub-window of an MDI area, or not.
        """
        if hasattr(self, 'mdi') and self.mdi is not None:
            self.mdi.closeActiveSubWindow()
        elif hasattr(self, 'parent') and hasattr(self.parent, 'closeActiveSubWindow'):
            self.parent.closeActiveSubWindow()
        elif hasattr(self, 'parent') and hasattr(self.parent, 'mdi'):
            self.parent.mdi.closeActiveSubWindow()
        else:
            self.close()
        return


class MySQLMixin(object):
    """Methods for dealing with the MySQL database.

    TODO: move this from the gui package to a model (as in MVC) package.
    """

    def executeUpdateQuery(self, query):
        """Execute a query that needs to be committed to the database.
        For example, an INSERT or UPDATE query.
        """
        config = Config.dbinfo().copy()
        db = connector.Connect(**config)             
        cursor = db.cursor()
        cursor.execute(query)
        db.commit()
        cursor.close()
        db.close()
        return
    
    def executeResultsQuery(self, query):
        """Execute a query for which the database will return results.
        For example a SELECT query.
        """
        config = Config.dbinfo().copy()
        db = connector.Connect(**config)              
        cursor = db.cursor()
        cursor.execute(query)
        results = cursor.fetchall()
        cursor.close()
        db.close()
        return results

    
    def executeMultipleUpdateQueries(self, queries):
        """This method is idential to self.executeUpdateQuery
        except that it takes a list of query strings and executes each in turn
        """
        config = Config.dbinfo().copy()
        db = connector.Connect(**config)   
        
        cursor = db.cursor()
        for query in queries:
            cursor.execute(query)
            db.commit()
        cursor.close()
        db.close()
        return

    def executeMultipleResultsQueries(self, queries):
        """This method is idential to self.executeResultsQuery
        except that it takes a list of query strings, executes each in turn
        and returns a corresponding list of results.
        """
        results = []        
        config = Config.dbinfo().copy()
        db = connector.Connect(**config)             
        cursor = db.cursor()
        for query in queries:
            cursor.execute(query)
            result = cursor.fetchall()
            results.append(result)
        cursor.close()
        db.close()
        return results
    
    
class DataEntryMixin(object):
    
    def getDbString(self, strSeed):
         return strSeed.replace("'", "xxx")

    def getViewString(self, strSeed):
         return strSeed.replace("xxx", "'")

    def getStringMonth(self, month):
        return {"1" : "January","2" : "February", "3" : "March", "4" : "April",
                "5" : "May","6" : "June", "7" : "July","8" : "August",
                "9" : "September","10" : "October","11" : "November",
                "12" : "December"}[month]

    def getIntMonth(self, month):
        return {"January":"1","February":"2","March": "3", "April":"4" ,
                 "May":"5" ,"June":"6", "July":"7","August":"8",
                 "September":"9","October":"10","November":"11" ,
                 "December":"12"}[month]
