import urllib2

from lib_python import logger


def download_file(url, file_path):
    """
    Downloads a file from given cap to given file path. Handles GZIP encoding-compression.

    :rtype: bool
    :returns True, provided that file has been successfully downloaded, False otherwise
    :param url: URL to download the file from
    :param file_path: file path to download the URL result into
    """

    # Open the cap
    try:
        request = urllib2.Request(url)
        request.add_header('Accept-encoding', 'gzip, deflate')
        f = urllib2.urlopen(request)

        logger.debug("Downloading from URL: {0}".format(url))

        # open local file for writing
        with open(file_path, "wb") as local_file:
            local_file.write(f.read())

    # handle errors
    except urllib2.HTTPError, ex:
        logger.error("HTTP Error at URL {0}: {1}".format(url, ex.reason))
        return False

    except urllib2.URLError, ex:
        logger.error("URL Error at URL {0}: {1}".format(url, ex.reason))
        return False

    return True
