def dic2hashtable(dic=None):
    """Wandelt ein Jython-Dictonary in einen JAVA-Hashtable um.

    dic2hashtable(dic)
    dic: Jython-Dictonary (e.g. {'a':1,'b':2})
    """
    from java.util import Hashtable

    d=dic.copy()
    res=Hashtable()
    while (len(d)>0):
        (key,value)=d.popitem()
        res.put(key,value)
    return res

def dic2hashmap(dic=None):
    """Wandelt ein Jython-Dictonary in einen JAVA-HashMap um.

    dic2hashmap(dic)
    dic: Jython-Dictonary (e.g. {'a':1,'b':2})
    """
    from java.util import HashMap

    d=dic.copy()
    res=HashMap()
    while (len(d)>0):
        (key,value)=d.popitem()
        res.put(key,value)
    return res


def showVisualisation(visName,games=None,mappings=None,name=None,show=1):
    """Shows a visualisation given the visualisation's name.

    showVisualisation(visName, games=None, mappings=None)
    visName:  The name of the visualisation
    games:    The games to act on. If None fipm will be queried for the games.
    mappings: The parameters of the query, e.g. {\"players\": \"1,2,3,4\"}.
    """
    from fipm.data import StoredVisualisation
    from de.tum.in.fipm.base.util import Settings

    fipm=Settings.getStd().get("main_desktop");
    svis=StoredVisualisation.readVisualisation(visName)
    #    if games==None:
    #        games=fipm.getSelectedGames()
    games=updateGames(games)
    if mappings!=None:
        mappings=dic2hashtable(mappings)
    #    return (svis, games, mappings)
    viss=svis.execute(games,mappings)
    frames=[]
    for visNo in range(viss.size()):
        vis=viss.get(visNo)
        frame=StoredVisualisation.getVisualisationFrame(vis)
        if name!=None:
            frame.setTitle(name)
        if show:
            fipm.addView(frame)
        frames.append(frame)
    return frames

def getQueryResult(queryName,games=None,mappings=None):
    """Returns the result of a Query.

    getQueryResult(queryName,games=None,mappings=None)
    queryName: The name of the Query
    games:    The games to act on. If None fipm will be queried for the games.
    mappings: The parameters of the query, e.g. {\"players\": \"1,2,3,4\"}.
    """
    from de.tum.in.fipm.base.database import SQLQuery
    from de.tum.in.fipm.base.data.query import QueryFactory
    from fipm.gui import InteractiveQuery
    from de.tum.in.fipm.base.util import Settings

    fipm=Settings.getStd().get("main_desktop");
    q=QueryFactory.readQuery(queryName)
    games=updateGames(games)
    #    if games==None:
    #        games=fipm.getSelectedGames()
    if mappings!=None:
        mappings=dic2hashtable(mappings)
        q.setParameters(mappings)
#    return (svis, games, mappings)
    qr=q.execute(games)
    return qr

def execFeature(featureName, qrs, mappings, groupings):
    """ Calculate a feature on a set of QueryResult.
    
    execFeature(featureName, qrs, mappings, groupings)
    qrs: QueryResults
    mappings: mapping from featureInputName to [queryNum, columnIdx]
    groupings: the grouping columns [queryNum, columnIdx]
    """
    from de.tum.in.fipm.base.data.feature import QueryFeature
    from java.util import HashMap
    
    from jarray import array
    
    feature=QueryFeature.getFeature(featureName)
    fmappings=HashMap()
    for key in mappings.keys():
        qc=mappings[key]
        fmappings.put(key,array(qc, "i"))
    return feature.calculateFeature(fmappings, groupings, qrs)

def updateGames(games):
    """Updates the games if games==None.

    Gets the selected games or a standard game if none is selected
    """
    from jarray import *
    from utils import *
    from de.tum.in.fipm.base.data import GameData
    from de.tum.in.fipm.base.util import Settings
    from javax.swing import JOptionPane

    if games==None:
        fipm=Settings.getStd().get("main_desktop")
        games=fipm.getSelectedGames()
        if games==None or len(games)<1:
            JOptionPane.showMessageDialog(fipm,\
                "No game selected: Using standard",\
                "Game selection",JOptionPane.WARNING_MESSAGE)
            games=array([fipm.getAllGames()[2]],GameData)
    return games

def showdectree(nc):
    """Shows a decision tree in a window.

    showdectree(nc)
    nc: a NamedClassifier object representing a decision tree
    """
    from fipm.gui.game.view import RuleFrame
    from de.tum.in.fipm.base.util import Settings
    from java.lang import StringBuffer
    from javax.swing import JLabel

    fipm=Settings.getStd().get("main_desktop")
    rules=nc.getRules()
    f=RuleFrame(rules)
    fipm.addView(f)
    return f


def execSQLonResult(select,where,result):
    """Executes an SQLQuery on a QueryResult.

    execSQLonResult(select,where,result)
    select: Everything before the FROM
    where:  Everything after the FROM ...
    result: The QueryResult
    The QueryResult is written to Database and then
    the SQL statement is executed on this table
    """
    from de.tum.in.fipm.base.util import Settings
    from de.tum.in.fipm.base.database import SQLQuery
    from fipm.gui import InteractiveQuery
    from fipm.data.db.base import DBQueryResultIO
    qrio=DBQueryResultIO.getInstance()
    dbengine=Settings.getStd().get("main_dbengine")
    cachedb=Settings.getStd().get("primary_cache")
    dbengine.update("DROP TABLE IF EXISTS "+cachedb+".tmp_jython")
    qrio.save("tmp_jython", result)
    query=select+" FROM "+cachedb+".tmp_jython "+where
    qr=InteractiveQuery(SQLQuery(None,query,None)).execute(result.getGame())
    dbengine.update("DROP TABLE "+cachedb+".tmp_jython")
    return qr
    
def createQueryResult(colnames, signature, data, game=None):
	"""Creates a QueryResult with the given columnnames, signature and data
	
	createQueryResult(colnames, signature, data)
	colnames : the names of the columns
	signature: the types of the columns
	data     : the data in table form (2 times for ... in ...)
	returns the QueryResult
	"""
	
	from de.tum.in.fipm.base.data import QueryResult
	qr=QueryResult()
	for i in range(0,len(colnames)):
		qr.addColumn(colnames[i],signature[i])
	i=0
	for row in data:
		j=0
		qr.addRow(-1)
		for element in row:
			qr.setElement(i,j,element)
                        if game!=None:
                            qr.setGame(i,game)
			j=j+1
		i=i+1
        if game!=None:
            qr.setGame(game)
	return qr

def removedirs(path):
    """ Remove a path recursively

    removedirs(path)
    path : the directory to remove
    """
    import os

    files=os.listdir(path)
    for file in files:
        if os.path.isdir(path+os.sep+file):
            removedirs(path+os.sep+file)
        else:
            os.remove(path+os.sep+file)
    os.rmdir(path)

def maxIndex(values):
    """ Get the index of the maximum value in an array

    maxIndex(values)
    values : the array
    """
    max=values[0]
    maxIdx=0
    for i in range(len(values)):
        if max<values[i]:
            maxIdx=i
            max=values[i]
    return maxIdx

def getFIPM():
    """ Get the main_desktop from settings where FIPM is stored
    """
    from de.tum.in.fipm.base.util import Settings
    return Settings.getStd().get("main_desktop")
