# -*- coding:utf-8 -*-
# misc.py
# 
# Copyright (C) 2005-2007 Mykola Lynnyk <pydefiner@gmail.com>
# Copyright (C) 2008 Stefan J. Betz <stefan_betz@gmx.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from sys import argv
from os import getenv, environ, access, F_OK, X_OK
from os.path import exists, dirname, abspath, join, split, basename
from optparse import OptionParser
from Queue import Queue
from ConfigParser import NoSectionError
from gtk import STOCK_DIALOG_ERROR, STOCK_DIALOG_INFO, STOCK_DIALOG_WARNING

# pyNeighborhood Version
version = '0.5.4'

# Global Variable Definitions
options = None

# Global event queue
events = Queue()

# Notification globals
INFO = 0
WARNING = 1
ERROR = 2

# Function Definitions
def unpad(mystr):
    """
    Removes more than one Space in the String 'str'
    """
    unpaded = []
    for item in mystr.split(" "):
        temp = item.strip()
        if temp != "":
            unpaded.append(temp)
    result = " ".join(unpaded)
    return result

def sharepath(item=''):
    if exists(join(dirname(abspath(argv[0])),"pyneighborhood")):
        return join(dirname(abspath(argv[0])), item)
    else:
        return join(split(dirname(argv[0]))[0], 'share', 'pyneighborhood', item)

def homeconfdir():
    """
    This Function returns the User Configuration Path (~/.pyNeighborhood)
    """
    return getenv("HOME") + "/.pyNeighborhood"

def get_desktop_environ():
    """
    This function tries to determine the user's running desktop environment
    and returns its result, or False otherwise
    """
    if environ.get("GNOME_DESKTOP_SESSION_ID"):
        desktop_env = "gnome"
    elif environ.get("KDE_FULL_SESSION"):
        desktop_env = "kde"
    elif environ.get("XDG_CURRENT_DESKTOP") == "LXDE":
        desktop_env = "lxde"
    elif environ.get("DESKTOP_SESSION") == "xfce":
        desktop_env = "xfce"
    else:
        desktop_env = False
    return desktop_env

def parse_args():
    """
    Parse Command Line Arguments
    """
    def print_version(option, opt_str, value, parser, *args, **kwargs):
        print "pyNeighborhood %s" % version
        raise SystemExit
    parser = OptionParser()
    parser.add_option("-v", "--version", action="callback", callback=print_version,
                        help="Print pyNeighborhood Version")
    global options # Don't remove this, because "options" is then everytime "None"!
    options, args = parser.parse_args()

def push_notification(message, level = 0):
    """
    Push a information or error message on the global event queue.

    level 0 -> Information
    level 1 -> Warning
    level 2 -> Error
    """
    if level == INFO:
        icon = STOCK_DIALOG_INFO
    elif level == WARNING:
        icon = STOCK_DIALOG_WARNING
    elif level == ERROR:
        icon = STOCK_DIALOG_ERROR
    else:
        # if someone specified an unknow level, fallback to level 0
        icon = STOCK_DIALOG_INFO
    from pyneighborhood import config
    try:
        loglevel = int(config.get('Main','loglevel'))
    except NoSectionError:
        loglevel = 0
    if loglevel != -1 and level >= loglevel:
        events.put((icon, message))

def check_executable(executable):
    """
    Check if executable is a valid filename and the executable bit is set.
    """
    return True if access(executable,F_OK+X_OK) else False

# Simple Exception based MountpointError exception
class MountpointError(Exception):
    """
    Exception raised when creating or accessing 
    the mountpoint fails in mountwindow 
    """
    pass
