# Copyright (c) 2004 Infrae. All rights reserved.
# See also LICENSE.txt

import os
import urllib
from AccessControl import getSecurityManager
from AccessControl.PermissionRole import rolesForPermissionOn

def add_and_edit(context, id, REQUEST, screen='manage_main'):
    """Helper function to point to the object's management screen if
    'Add and Edit' button is pressed.

    id -- id of the object we just added
    """
    if REQUEST is None:
        return
    try:
        u = context.DestinationURL()
    except:
        u = REQUEST['URL1']
        
    if REQUEST.has_key('submit_edit'):
        u = "%s/%s" % (u, urllib.quote(id))
        REQUEST.RESPONSE.redirect(u+'/'+screen)
    else:
        REQUEST.RESPONSE.redirect(u+'/manage_main')

def checkPermission(permission, obj):
    ''' utility function stolen from CMF and made CMF independent'''
    roles = rolesForPermissionOn(permission, obj)
    if type(roles) in (type(''),type(u'')):
        roles=[roles]
    if getSecurityManager().getUser().allowed( obj, roles ):
        return 1
    return 0

def get_realm():
    """Return the authentication realm this Zope is configured with.

    If there isn't a Z_REALM environment variable, 'Zope' is returned.
    """
    try:
        realm = os.environ['Z_REALM']
    except KeyError:
        # no realm set in environment
        # return a dummy one
        realm = 'Zope'
        pass
    return realm

def decodePropertyDict(propdict, source_encoding='UTF-8'):
    """Return a dict where all keys and values are unicode
    """
    ret = {}
    for (n, ns), value in propdict.iteritems():
        n = n.decode(source_encoding)
        ns = ns.decode(source_encoding)
        value = value.decode(source_encoding)
        ret[(n, ns)] = value
    return ret

def encodePropertyDict(propdict, target_encoding='UTF-8'):
    """Return a dict where all keys and values are encoded
    """
    ret = {}
    for (n, ns), value in propdict.iteritems():
        n = n.encode(target_encoding)
        ns = ns.encode(target_encoding)
        value = value.encode(target_encoding)
        ret[(n, ns)] = value
    return ret
