# Copyright (c) 2001, 2002 by Intevation GmbH
# Authors:
# Bernhard Herzog <bh@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

"""
Functions to deal with filenames
"""

__version__ = "$Revision: 2875 $"

import os
import os.path
import sys
from tempfile import mktemp

from string import join

from Thuban import _

def relative_filename_common(dir, absname, sep):
    """Return a filename relative to dir for the absolute file name absname.
    This is part the posix and nt versions have in common. Both dir and
    absname are assumed to be normalized (as done with os.normpath)
    absolute filenames without drive letters. sep is the platform
    specific directory separator.
    """

    # split the filenames into their components. remove the first item
    # since it will be always empty because both names are absolute.
    dir_parts = dir.split(sep)[1:]
    absname_parts = absname.split(sep)[1:]

    # count the number of common parts at the start of dir_parts and
    # absname_parts
    max_common = min(len(dir_parts), len(absname_parts))
    common = 0
    while common < max_common and dir_parts[common] == absname_parts[common]:
        common = common + 1

    # If the common part is the root directory, return absname
    if common == 0:
        return absname

    # for each directory under the common part prepend a '..'.
    rel_parts = (len(dir_parts) - common) * ['..'] + absname_parts[common:]
    return join(rel_parts, sep)
    

def relative_filename_posix(dir, absname):
    """Return a filename relative to dir for the absolute file name absname.

    If absname is already a relative filename, return it unchanged. If
    the common directory of dir and absname is /, return absname
    unchanged. If dir is not an absolute name, raise TypeError.

    This is the posix specific version of relative_filename.

    Example:
    >>> from fileutil import relative_filename_posix
    >>> relative_filename_posix("/usr/local/lib/", "/usr/local/lib/python")
    'python'
    >>> relative_filename_posix("/usr/local/lib/", "/usr/local/bin/python")
    '../bin/python'
    >>> relative_filename_posix("/usr/local/lib/", "/usr/bin/python")
    '../../bin/python'
    >>> relative_filename_posix("/usr/local/lib/", "/var/spool/mail")
    '/var/spool/mail'
    >>> relative_filename_posix("/home/", "xyzzy")
    'xyzzy'
    >>> relative_filename_posix("home/", "/xyzzy")
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "fileutil.py", line 42, in relative_filename_posix
        raise TypeError("first argument must be an absolute filename")
    TypeError: first argument must be an absolute filename
    """
    # for posix, the common part does exactly what we need, except for
    # the special cases and input checking. Import posixpath explicitly
    # for that to faciliate testing
    import posixpath
    if not posixpath.isabs(absname):
        return absname

    if not posixpath.isabs(dir):
        raise TypeError(_("first argument must be an absolute filename"))

    dir = posixpath.normpath(dir)
    absname = posixpath.normpath(absname)

    return relative_filename_common(dir, absname, "/")

def relative_filename_nt(dir, absname):
    r"""Return a filename relative to dir for the absolute file name absname.

    If absname is already a relative filename or if dir and absname are
    on different drives, return absname. If the common directory of dir
    and absname is the drive's root directory, return absname. If dir is
    not an absolute name or either name doesn't have a drive letter,
    raise TypeError.

    This is the nt specific version of relative_filename.

    Example:
    >>> from fileutil import relative_filename_nt
    >>> relative_filename_nt(r"C:\Programme\Python", r"C:\Programme\Thuban")
    '..\\Thuban'
    >>> relative_filename_nt(r"C:\Programme\Python", r"D:\Programme\Thuban")
    'D:\\Programme\\Thuban'
    >>> relative_filename_nt(r"C:\Programme\Python", r"C:Programme")
    'C:Programme'
    >>> relative_filename_nt(r"C:Programme\Python", r"C:Programme")
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "fileutil.py", line 123, in relative_filename_nt
        raise TypeError("first argument must be an absolute filename")
    TypeError: first argument must be an absolute filename
    >>> relative_filename_nt(r"\Programme\Python", r"\Programme")
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "fileutil.py", line 120, in relative_filename_nt
        raise TypeError("Both parameters must have a drive letter")
    TypeError: Both parameters must have a drive letter
    """
    # first check the parameters. Imort ntpath directly to facilitate
    # testing on non-nt systems.
    import ntpath

    dir = ntpath.normpath(dir)
    absname = ntpath.normpath(absname)

    dir_drive, dir_rest = ntpath.splitdrive(dir)
    absname_drive, absname_rest = ntpath.splitdrive(absname)
    #print dir_drive, dir_rest
    #print absname_drive, absname_rest
    if not dir_drive or not absname_drive:
        raise TypeError(_("Both parameters must have a drive letter"))

    if not ntpath.isabs(dir_rest):
        raise TypeError(_("first argument must be an absolute filename"))

    # handle some special cases
    if not ntpath.isabs(absname_rest):
        return absname

    if dir_drive != absname_drive:
        return absname

    # Now both dir_rest and absname_rest are absolute filenames without
    # drive letter. We can now use the common part to determine the
    # relative name
    return relative_filename_common(dir_rest, absname_rest, "\\")

def get_application_dir():
    """Determine the path to the .thuban directory. Create the directory
    if it doesn't exist.

    Under posix systems use the os.expanduser() method.
    Under Win32 try to read the "Explorer/Shell Folders/" value "AppData".
    """
    if os.name == 'posix':
        dir = os.path.expanduser("~/.thuban")
        if not os.path.isdir(dir):
           os.mkdir(dir)
        return dir
    elif os.name == 'nt':
        regkey = 1
        try:
            import _winreg as wreg
        except ImportError:
            regkey = 0

        if regkey:
            try:
                key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, 
                  "Software\\Microsoft\\Windows\\CurrentVersion\\"\
                  "Explorer\\Shell Folders")
                dir = wreg.QueryValueEx(key, "AppData")[0]
                dir = os.path.join(dir, "thuban")
            except:
                regkey = 0

        if not regkey:
            # The fallback. This should result in something like the 
            # user directory ...
            guess = os.path.dirname(
                                os.path.dirname(os.path.dirname(mktemp()))
                            )
            dir = os.path.join(guess, "thuban")
        if not os.path.isdir(dir):
           os.mkdir(dir)
        
        return str(dir)

    else:
        raise RuntimeError(_("No implementation of get_application_dir"
                       " available for platform") + os.name)

def get_thuban_dir():
    """Determine the path to the where the Thuban directory is stored 

    This method is needed to solve problems when the application is frozen
    """
    if hasattr(sys, 'frozen'):
        res_path = os.path.normpath(os.path.dirname(sys.executable))
    else:
        res_path = os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir ,os.pardir))
    return res_path

# bind the appropriate version of relative_filename for the platform
# we're currently running on.
if os.name == "posix":
    relative_filename = relative_filename_posix
elif os.name == "nt":
    relative_filename = relative_filename_nt
else:
    raise RuntimeError(_("No implementation of relative_filename"
                       " available for platform") + os.name)

__test__ = {"relative_filename_posix": relative_filename_posix,
            "relative_filename_nt": relative_filename_nt}

# if run as a script, run doctest
def _test():
    import doctest, fileutil
    # Pass an isprivate function that always returns true so that only
    # items in __test__ are tested
    return doctest.testmod(fileutil, isprivate = lambda *args: 1)
    
if __name__ == "__main__":
    _test()
