# -*- coding: utf-8 -*-
# Elisa - Home multimedia server
# Copyright (C) 2006-2008 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Elisa with Fluendo's plugins.
#
# The GPL part of Elisa is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Elisa" in the root directory of this distribution package
# for details on that license.

"""
Miscellaneaous utilities that don't need their own module because they are
reasonnably small.
"""

__maintainer__ = 'Philippe Normand <philippe@fluendo.com>'

import mimetypes
import sys, platform
import os, re
from twisted.internet import defer

def env_var_expand(var_name):
    """
    Expand the given environment variable content. If it contains
    other references to environment variables, they are expanded too.

    Supported platforms are win32 and linux.
    
    Example of use::

       >>> env_var_expand('$HOME')
       >>> '/home/phil'

    @raises ValueError: if current system's platform is not windows or linux
    @param var_name:    environment variable
    @type var_name:     string
    @rtype:             string
    """
    platform_type = platform.system().lower()
    if platform_type == 'windows':
        re_env = re.compile(r'%(\w+)%')
        def expander(mo):
            return os.environ.get(mo.group()[1:-1], 'UNKNOWN')
        
    elif platform_type == 'linux':
        re_env = re.compile(r'\$(\w+)')
        
        def expander(mo):
            xpanded = os.environ.get(mo.group()[1:], 'UNKNOWN')
            if xpanded.find('$') > -1:
                xpanded = re_env.sub(expander, xpanded)
            return xpanded
        
    else:
        raise ValueError("Unsupported platform")
    
    expanded = re_env.sub(expander, var_name)
    return expanded

def env_var_explode_list(var_name, default=''):
    """
    Explode a list of values stored in an environment variable as a
    single string. On win32 the item separator is ';' and on other
    platforms it is ':'.

    Example of use::

       >>> env_var_explode_list('$PATH')
       >>> ['/usr/bin','/bin']
    
    @param var_name:    environment variable
    @type var_name:     string
    @keyword default:   value to use if environment variable not found
    @type default:      string
    @rtype:             list of strings
    """
    value = os.environ.get(var_name, default)
    platform_type = platform.system().lower()
    if platform_type == 'windows':
        separator = ';'
    else:
        separator = ':'
    exploded = value.split(separator)
    if exploded == ['']:
        exploded = []
    return exploded
    

def un_camelify(camel_string):
    """
    Convert CamelCase styled strings to lower_cased style.

    @param camel_string: CamelStyled string to convert
    @type camel_string:  string
    @rtype:              string
    """
    if len(camel_string) < 2:
        un_cameled = camel_string.lower()
    else:
        camel_string = camel_string.replace(' ', '')
        un_cameled = camel_string[0].lower()
        for letter in camel_string[1:]:
            if letter.isupper():
                un_cameled += '_%s' % letter.lower()
            else:
                un_cameled += letter
    return un_cameled

def get_media_infos_from_mime(uri):
    """
    Retrieve mime-type and media type of the given URI, based on its
    extension.

    DEPRECATED !!!

    @param uri: the media resource address to analyze
    @type uri:  L{elisa.core.media_uri.MediaUri}
    @rtype:     2-tuple: (mime_type: string, file_type: string)
    """
    pass
    # TODO: remove this function when mime_getter works
    mime_type = mimetypes.guess_type(uri.path)
    if mime_type[0]:
        parts = mime_type[0].split('/')
        mime_type = mime_type[0]
        # Special cases handling
        if parts[0] == 'application':
            ext = uri.extension
            custom_extensions = {'ogg': 'audio',
                                 }
            file_type = custom_extensions.get(ext, '')
        else:
            file_type = parts[0]

        blacklist = ['x-mpegurl',]
        if parts[1] in blacklist:
            mime_type = ''
            file_type = ''
    else:
        # in case mimetypes did not return anything, filter on extension
        custom_extensions = {'flv': 'video',
                             'ogm': 'video',
                             'mkv': 'video',
                             'mod': 'video',
                             'nef': 'image'
                             }
        file_type = custom_extensions.get(uri.extension, '')
        if mime_type == (None, None):
            mime_type = ''
    return mime_type, file_type

# cache the result of the first is_hildon_desktop_running call
_hildon_desktop_running = None

def is_hildon_desktop_running():
    global _hildon_desktop_running

    try:
        import dbus
    except ImportError:
        _hildon_desktop_running = False
        return False

    if _hildon_desktop_running is not None:
        # return the cached value
        return _hildon_desktop_running
    try: 
        bus = dbus.SystemBus()
        driver = bus.get_object(dbus.BUS_DAEMON_NAME,
            dbus.BUS_DAEMON_PATH, dbus.BUS_DAEMON_IFACE)
        iface = dbus.Interface(driver, dbus.BUS_DAEMON_IFACE)
        _hildon_desktop_running = \
            bool(iface.NameHasOwner('com.nokia.hildon-desktop'))
    except dbus.DBusException:
        # it fails so we assume it is not hildon
        _hildon_desktop_running = False
        return False

    return _hildon_desktop_running

def get_distro():
    DISTROS = {
	"Ubuntu" : "/etc/lsb-release",
	"Debian" : "/etc/debian_version",
	#"RedHat" : "/etc/redhat-release",
	"SUSE" : "/etc/SUSE-release",
	"Fedora" : "/etc/fedora-release",
	"Gentoo" : "/etc/gentoo-release",
	"Slackware" : "/etc/slackware-version",
	"Mandriva" : "/etc/mandriva-release",
	"Mandrake" : "/etc/mandrake-release",
	"YellowDog" : "/etc/yellowdog-release",
	"SUN JDS" : "/etc/sun-release",
	"UnitedLinux" : "/etc/UnitedLinux-release"
	}
	
    for name,location in DISTROS.iteritems():
	try:
	    distroFile = open("%s" % location,"r")
	    content = distroFile.readlines(); distroFile.close();
	except:
	    pass
	else:
	    return name
    return 'Unknown'	
