from django.contrib.staticfiles.storage import staticfiles_storage
from django.contrib.sites.models import Site
from ldt import settings
import httplib2
import re
import urlparse


def absstatic(request, path):
    if request.is_secure():
        domain = "https://%s" % Site.objects.get_current().domain
    else:
        domain = "http://%s" % Site.objects.get_current().domain
    new_path = staticfiles_storage.url(path)
    return urlparse.urljoin(domain, new_path)

def request_with_auth(url, method='GET'):
    h = httplib2.Http()
    web_auth = settings.WEB_AUTH if settings.WEB_AUTH else []
    for entry in web_auth:
        if not isinstance(entry, dict):
            continue
        regex = entry.get('REGEX', None)
        if regex and re.search(regex, url, re.IGNORECASE):
            h.add_credentials(entry.get('NAME', ''), entry.get('PASSWORD', ''), entry.get('DOMAIN', ''))
            break
            
    return h.request(url, method)


def is_absolute(url):
    return bool(urlparse.urlparse(url).scheme)