#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      oeffner
#
# Created:     16/12/2013
# Copyright:   (c) oeffner 2013
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import sys, os


def Roundoff(val, precision):
    if isinstance(val, float):
        formatstr = "%2." + str(precision) + "f"
        return float(formatstr %float(val))
    if isinstance(val, list):
        for i,v in enumerate(val):
            val[i] = Roundoff(v, precision)
    return val


def RecaseFilename2(path):
    # need to specify current directory if only a filename is supplied
    if os.path.dirname(path) == "":
        path = os.path.join(".", path)
    #Get a case-insensitive path for use on a case sensitive system.
    return _path_insensitive(path) or path


def _path_insensitive(path):
    """
    Recursive part of path_insensitive to do the work.
    """
    if path == '' or os.path.exists(path):
        return path

    base = os.path.basename(path)  # may be a directory or a file
    dirname = os.path.dirname(path)

    suffix = ''
    if not base:  # dir ends with a slash?
        if len(dirname) < len(path):
            suffix = path[:len(path) - len(dirname)]

        base = os.path.basename(dirname)
        dirname = os.path.dirname(dirname)

    if not os.path.exists(dirname):
        dirname = _path_insensitive(dirname)
        if not dirname:
            return
    # at this point, the directory exists but not the file
    try:  # we are expecting dirname to be a directory, but it could be a file
        files = os.listdir(dirname)
    except OSError:
        return

    baselow = base.lower()
    try:
        basefinal = next(fl for fl in files if fl.lower() == baselow)
    except StopIteration:
        return

    if basefinal:
        return os.path.join(dirname, basefinal) + suffix
    else:
        return


# Copying HomologySearches to bixcluster didn't completely preserve file name case.
# So we need to identify file paths but in a case insensitive manner before opening files
def RecaseFilename(fname, mylock=None):
    print "unrecased fname= " + fname
#    if sys.platform == "win32": # as filenames are case insensitive
#        return fname
# in case we're invoked by a separate thread we must protect os.chdir which acts globally
    if mylock != None:
        mylock.acquire()
    #
    dirs = fname.split(os.sep)
    curdir = os.getcwd()
    recasedpath = ""
    if dirs[0] == "": # for unix paths
        os.chdir(os.sep)
        recasedpath = os.sep
    #
    for dir in dirs:
        files = glob.glob("*")
        m = []
        for file in files:
            #print "file= %s, dir = %s " %(file, dir)
            m = re.findall(dir,file,re.IGNORECASE)
            if m != [] and len(dir) == len(file):
                recasedpath = os.path.join(recasedpath, m[0])
                #print "m[0], file= " + m[0] + ", " + file
                break
        #
        if dir != dirs[-1] and dir != "" and m != []:
            #print "m= %s, dir= %s" %(str(m), dir)
            #os.chdir(file)
            os.chdir(m[0])
    #
    os.chdir(curdir)
    if mylock != None:
        mylock.release()
    #
    print "recased fname= " + recasedpath
    return recasedpath



def PosixSlashFilePath(fpath):
    if sys.platform != "win32":
        mstr = ""
        for c in fpath:
            if c == "\\":
                mstr += "/"
            else:
                mstr += c
        return mstr
    else: # if unix platform
        mstr = ""
        for c in fpath:
            if c == "/":
                mstr += "\\"
            else:
                mstr += c
        return mstr
#        return fpath


