# -*- coding: utf-8 -*-
import logging
import urllib.request

logger = logging.getLogger(__name__)

DEFAULT_XIVO_VERSION_FILE = '/usr/share/xivo/XIVO-VERSION'

XIVO_VERSION_HEADER = 'X-XIVO-VERSION'


def get_xivo_version(path=DEFAULT_XIVO_VERSION_FILE):
    """Return the XiVO version string from `path`, stripped, or None if the
    file is missing, unreadable, or blank."""
    try:
        with open(path) as fobj:
            version = fobj.read().strip()
    except (IOError, OSError) as e:
        logger.info('Could not read XiVO version file %s: %s', path, e)
        return None
    return version or None


class XivoVersionHandler(urllib.request.BaseHandler):
    """urllib handler that adds the X-XiVO-Version header to every request."""

    def __init__(self, version):
        self._version = version

    def http_request(self, req):
        req.add_unredirected_header(XIVO_VERSION_HEADER, self._version)
        return req

    https_request = http_request


def plugin_download_handlers(proxies, xivo_version_file=DEFAULT_XIVO_VERSION_FILE):
    """Return the urllib handlers for the PluginManager downloader: the usual
    proxy handlers plus an X-XIVO-VERSION handler when a version is available."""
    from provd.plugins import _new_handlers  # lazy import: plugins.py imports this module
    handlers = _new_handlers(proxies)
    version = get_xivo_version(xivo_version_file)
    if version:
        handlers.append(XivoVersionHandler(version))
    return handlers
