#
# -*- coding: utf-8 -*-

'''Simple general functions mainly dealing with list manipulations.
'''

############################################################################################################
#
#   IMPORTS
#
#===========================================================================================================

from types import *
import os, sys


############################################################################################################
#
#   GENERAL FUNCTIONS
#
#===========================================================================================================



# ------------------------------------------------------------------------------------
def multiplyLoL(inLoL):
    '''Takes a list of lists and multiplies each list with each other (like matrices).
    The reulting list contains lists with the same length.
    Returns the new list of lists.'''
    resultLoL = [[]]
    for list in inLoL:
        tmpLoL = []
        if len(list) > 0:
            for entry in list:
                for tmpList in resultLoL:
                    tmpLoL.append(tmpList+[entry])
        else:
            tmpLoL =resultLoL
        resultLoL = tmpLoL
    return resultLoL

# ------------------------------------------------------------------------------------
def mergeLoL(LoL1, LoL2):
    mergedLoL = []
    maxLen1 = 0
    maxLen2 = 0
    # if list2 is longer than list1 append empty lists
    while len(LoL1) < len(LoL2):
        LoL1.append([])
    # get largest sublist
    if len(LoL1) > 0:
        maxLen1 = max([len(x) for x in LoL1])
    if len(LoL2) > 0:
        maxLen2 = max([len(x) for x in LoL2])
    i = 0
    for a in LoL1:
        a = list(a)
        while len(a) < maxLen1:
            a.append(None)
        if i < len(LoL2):
            newSlice = list(LoL2[i])
        else:
            newSlice = []
        while len(newSlice) < maxLen2:
            newSlice.append(None)
        a += newSlice
        mergedLoL.append(a)
        i += 1
    return mergedLoL
    
# ------------------------------------------------------------------------------------
def scalarpNoList(item):
    '''Tests whether an item is not a list sequence.
    '''
    if type(item) == type([1,2]): return 0
    else: return 1

# ------------------------------------------------------------------------------------
def scalarpNoListOrTuple(item):
    '''Tests whether an item is not a tuple or list sequence.
    '''
    if type(item) in (type([1,2]), type( (1,2) )): return 0
    else: return 1
    
# ------------------------------------------------------------------------------------
def flatten(sequence, scalarp=scalarpNoList, result=None):
    '''Flatten a nested list to one flat list.'''
    if result is None: result = []
    for item in sequence:
        if scalarp(item): result.append(item)
        else: flatten(item, scalarp, result)
    return result
    
# ------------------------------------------------------------------------------------
def normalizeWhitespace(x):
    '''Return the string x with normalized whitespace.'''
    return " ".join(x.split())
    
# ------------------------------------------------------------------------------------
def isTrue(arg):
    """function to simulate a boolean value test.
    Takes strings or numbers.
    Returns 1 if number==1 OR if string is 'true' (case insensitive)."""
    try:
        arg =str(arg)
        arg = arg.strip()
        arg = arg.lower()
        if arg in ('1', 'true','on','checked'):
            return 1
        else:
            return 0
    except:
        return 0

# ------------------------------------------------------------------------------------
def unique(alist):
    '''Remove duplicates from list while preserving order.'''
    set = {}
    return [set.setdefault(e,e) for e in alist if e not in set]
    
# ------------------------------------------------------------------------------------
def intersects(alist, blist):
    '''Returns the intersection of two lists.'''
    return [a for a in alist if a in blist]
    
# ------------------------------------------------------------------------------------
def determineServerIP():
    from socket import gethostname, gethostbyname
    host = gethostbyname(gethostname())
    if len(host) < 2:
        host = gethostname()
    return host

# ------------------------------------------------------------------------------------
def getPyLibDir():
    pylib = None
    if sys.platform in ('dos','win32','win16','os2'):
        pylib = os.path.join(sys.prefix,'lib')
    else:
        # all unix platforms including darwin
        for l in ('lib64','lib32','lib'):
            tmp = os.path.join(sys.prefix,l,'python%s'%sys.version[:3])
            if os.path.isdir(tmp):
                pylib = tmp
                break
    if pylib is None:
        raise "Cant find any Python library!"
    return pylib
    
def getCodecsDir():
    return os.path.join(getPyLibDir(),'encodings')
    
def getEncodingList():
    codecs = []
    codecDir = getCodecsDir()
    potCodecs = os.listdir(codecDir)
    potCodecs.sort()
    for codec in potCodecs:
        if codec.endswith('py') and codec not in ('__init__.py','aliases.py','undefined.py'):
            codecs.append( codec[:-3] )
    return codecs


#-------------------------------------------------------------------------------------------------------
def dictAsTable( d, indent=0 ):
    R = [ ]
    names = d.keys()
    names.sort()
    for name in names:
        value = d[ name ]
        if type(value) == DictType:
            value = '\n' + dictAsTable(d[ name ], indent+1)
        indentString = '  '*indent
        R.append( '%s%s:\t%s' % ( indentString, name, value, ) )
    R = '\n'.join( R )
    return R

#-------------------------------------------------------------------------------------------------------
def dictAsHtmlTable( d ):
    R = [ '<table border="1" cellspacing="0" cellpadding="1" style="font-size:85%">' ]
    names = d.keys()
    names.sort()
    for name in names:
        value = d[ name ]
        if type(value) == DictType:
            value = '\n' + dictAsHtmlTable(d[ name ])
        else:
            value = _esc( unicode(d[ name ]) )
        name_ = _esc( name )
        R.append( '<tr><td><b>%s</b></td><td>%s</td></tr>' % ( name_, value, ) )
    R.append( '</table>' )
    R = '\n'.join( R )
    return R

#-------------------------------------------------------------------------------------------------------
def environmentAsTable( html = False ):
    if html:
        return dictAsHtmlTable( _os.environ )
    else:
        return dictAsTable( _os.environ )






# ------------------------------------------------------------------------------------
if __name__ ==  "__main__":
    a = [ [1,2,3], (1,2,[3,4,5]), ['ah','k','klo'] ]
    print a
    print flatten(a, scalarpNoListOrTuple)
    print flatten(a)
    print "-"*20
    a = [(1,2,3,4), (4,5,6), (7,8,9)]
    b = [("w","e"), ("tzeqi","tqtrew","hansi"), ("fd","fd"), ("bernd","magda")]
    print mergeLoL(a,b)
    print mergeLoL(a,[])
    print mergeLoL([("ahoi",)],a)
    
