import socket
import urllib.error

from stillCenter.i18n import _


_OFFLINE_MARKERS = (
    "network is unreachable",
    "no route to host",
    "temporary failure in name resolution",
    "name or service not known",
    "offline",
)

_CONNECTIVITY_MARKERS = (
    "failed to connect",
    "could not connect",
    "cannot connect",
    "timed out",
    "connection refused",
    "connection reset",
    "host unreachable",
)


def get_error_reason(error) -> str:
    reason = getattr(error, "reason", error)
    return str(reason).strip() or str(error).strip() or _("Unknown error")


def is_connection_error(error) -> bool:
    if isinstance(error, urllib.error.HTTPError):
        return False

    reason = getattr(error, "reason", None)
    if isinstance(error, (urllib.error.URLError, TimeoutError, ConnectionError, socket.gaierror, OSError)):
        return True
    if reason is not None and isinstance(reason, (TimeoutError, ConnectionError, socket.gaierror, OSError)):
        return True

    reason_text = get_error_reason(error).lower()
    return any(marker in reason_text for marker in _OFFLINE_MARKERS + _CONNECTIVITY_MARKERS)


def get_connection_error_title(error) -> str:
    reason_text = get_error_reason(error).lower()
    if any(marker in reason_text for marker in _OFFLINE_MARKERS):
        return _("No network connection")
    return _("Unable to connect")


def build_connection_error_description(target: str, error) -> str:
    reason = get_error_reason(error)
    return _("Connect to the internet and try again to load {target}.\n\nDetails: {reason}").format(
        target=target,
        reason=reason
    )
