import os
import requests
import hashlib
from urlparse import urlparse
from sunburnt import sunburnt

from django.conf import settings
from django.contrib.sites.models import Site


def solr_interface():
    '''Wrapper function to initialize a
    :class:`sunburnt.SolrInterface` based on django settings and
    evironment.  Uses **SOLR_SERVER_URL** and **SOLR_CA_CERT_PATH** if
    one is set.  Additionally, if an **HTTP_PROXY** is set in the
    environment, it will be configured.
    '''

    session = requests.Session()

    if hasattr(settings, 'SOLR_CA_CERT_PATH'):
        session.cert = settings.SOLR_CA_CERT_PATH
        session.verify = True
    if getattr(settings, 'SOLR_DISABLE_CERT_CHECK', False):
        session.verify = False

    # configure requests to use http proxy if one is set in ENV
    http_proxy = os.getenv('HTTP_PROXY', None)
    if http_proxy:
        parsed_proxy = urlparse(http_proxy)
        session.proxies = {
           parsed_proxy.scheme: http_proxy   # i.e., 'http': 'hostname:3128'
        }

    # pass in the constructed requests session as the connection to be used
    # when making requests of solr
    solr_opts = {'http_connection': session}
    # since we have the schema available, don't bother requesting it
    # from solr every time we initialize a new connection
    if hasattr(settings, 'SOLR_SCHEMA'):
        solr_opts['schemadoc'] = settings.SOLR_SCHEMA

    solr = sunburnt.SolrInterface(settings.SOLR_SERVER_URL,
                                  **solr_opts)
    return solr


def md5sum(filename):
    '''Calculate and returns an MD5 checksum for the specified file.  Any file
    errors (non-existent file, read error, etc.) are not handled here but should
    be caught where this method is called.

    :param filename: ful path to the file for which a checksum should be calculated
    :returns: hex-digest formatted MD5 checksum as a string
    '''
    # duplicated from keep.common.utils
    # possibly at some point this should be moved to a common codebase/library
    md5 = hashlib.md5()
    with open(filename,'rb') as f:
        for chunk in iter(lambda: f.read(128* md5.block_size), ''):
            md5.update(chunk)
    return md5.hexdigest()


def absolutize_url(local_url):
    '''Convert a local url to an absolute url, with scheme and server name,
    based on the current configured :class:`~django.contrib.sites.models.Site`.

    :param local_url: local url to be absolutized, e.g. something generated by
        :meth:`~django.core.urlresolvers.reverse`
    '''
    if local_url.startswith('http'):
        return local_url

    # add scheme and server (i.e., the http://example.com) based
    # on the django Sites infrastructure.
    root = Site.objects.get_current().domain
    # 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

    # make sure there is no double slash between site url and local url
    if local_url.startswith('/'):
        root = root.rstrip('/')

    return root + local_url

@@ -2568,32 +2568,33 @@
 startswith('http
+s
 '):%0A        retu
@@ -2899,16 +2899,17 @@
 th('http
+s
 '):%0A    
@@ -2924,16 +2924,17 @@
  = 'http
+s
 ://' + r

fix thumbnail not loaded over https issue