from django.conf import settings
from django.utils.encoding import iri_to_uri
from django.core.urlresolvers import reverse
from pidservices.djangowrapper.shortcuts import DjangoPidmanRestClient


def absolutize_url(local_url):
    '''Convert a local url to an absolute url, with scheme and server name,
    based on settings.BASE_URL.

    :param local_url: local url to be absolutized, e.g. something generated by
    :meth:`~django.core.urlresolvers.reverse`
    '''
    # add server (i.e., the http://example.com) to localsettings
    #If admin section is ever activated, this logic should be moved to
    #:class:`~django.contrib.sites.models.Site
    root = settings.BASE_URL
    # but also add the http:// if necessary, since most sites docs
    # suggest using just the domain name
    if not root.startswith('http'):
        root = 'http://' + root
    return root + local_url



def get_pid_target(view_name):
    '''Get a pidman-ready target for a named view.'''

    ENCODED_PID_TOKEN = iri_to_uri(DjangoPidmanRestClient.pid_token)
    default_pidspace = getattr(settings, 'FEDORA_PIDSPACE', None)

    # first just reverse the view name.
    pid = '%s:%s' % (default_pidspace, DjangoPidmanRestClient.pid_token)
    target = reverse(view_name, kwargs={'pid': pid})
    # reverse() encodes the pid_token, so unencode just that part
    target = target.replace(ENCODED_PID_TOKEN, DjangoPidmanRestClient.pid_token)

    # reverse() returns a full path - absolutize so we get scheme & server also
    return absolutize_url(target)