import datetime
import json
import platform
import re
import ssl
import time
from urllib.parse import urlencode

from .version import VERSION, VERSION_INFO

__author__ = "EasyPost <oss@easypost.com>"
__version__ = VERSION
version_info = VERSION_INFO
SUPPORT_EMAIL = "support@easypost.com"
USER_AGENT = f"EasyPost/v2 PythonClient/{VERSION} Python/{platform.python_version()}"
TIMEOUT = 60

# config
api_key = None
api_base = "https://api.easypost.com/v2"

# use urlfetch as request_lib on google app engine, otherwise use requests
request_lib = None
try:
    from google.appengine.api import urlfetch

    request_lib = "urlfetch"
    # use the GAE application-wide "deadline" (or its default)
    timeout = urlfetch.get_default_fetch_deadline() or TIMEOUT
except ImportError:
    timeout = TIMEOUT
    try:
        import requests

        request_lib = "requests"
        requests_session = requests.Session()
        requests_http_adapter = requests.adapters.HTTPAdapter(max_retries=3)
        requests_session.mount("https://api.easypost.com", requests_http_adapter)
    except ImportError:
        raise ImportError(
            "EasyPost requires an up to date requests library. "
            'Update requests via "pip install -U requests" or '
            f"contact us at {SUPPORT_EMAIL}."
        )

    try:
        version = requests.__version__
        major, minor, patch = [int(i) for i in version.split(".")]
    except Exception:
        raise ImportError(
            "EasyPost requires an up to date requests library. "
            'Update requests via "pip install -U requests" or contact '
            f"us at {SUPPORT_EMAIL}."
        )
    else:
        if major < 1:
            raise ImportError(
                "EasyPost requires an up to date requests library. Update "
                'requests via "pip install -U requests" or contact us '
                f"at {SUPPORT_EMAIL}."
            )


class Error(Exception):
    def __init__(self, message=None, http_status=None, http_body=None, original_exception=None):
        super(Error, self).__init__(message)
        self.message = message
        self.http_status = http_status
        self.http_body = http_body
        self.original_exception = original_exception
        try:
            self.json_body = json.loads(http_body)
        except Exception:
            self.json_body = None

        self.param = None
        try:
            self.param = self.json_body["error"].get("param", None)
        except Exception:
            pass


def convert_to_easypost_object(response, api_key, parent=None, name=None):
    types = {
        "Address": Address,
        "Batch": Batch,
        "Brand": Brand,
        "CarrierAccount": CarrierAccount,
        "CustomsInfo": CustomsInfo,
        "CustomsItem": CustomsItem,
        "Event": Event,
        "Insurance": Insurance,
        "Order": Order,
        "Parcel": Parcel,
        "PaymentLogReport": Report,
        "Pickup": Pickup,
        "PickupRate": PickupRate,
        "PostageLabel": PostageLabel,
        "Rate": Rate,
        "Refund": Refund,
        "RefundReport": Report,
        "Report": Report,
        "ScanForm": ScanForm,
        "Shipment": Shipment,