# Path: roulier/exception.py
# class CarrierError(Exception):
#     """Error from WS.
# 
#     Use this class in your application to manage
#     exception with the carrier WS
#     """
# 
#     def __init__(self, response, msg=None):
#         if msg is None:
#             msg = "An error occured with WS"
#         super(CarrierError, self).__init__(msg)
#         self.response = response
#         if self.response:
#             if hasattr(self.response, "text"):
#                 log.debug(response.text)
#             else:
#                 log.debug(response)
# 
# Path: roulier/transport.py
# class RequestsTransport(ABC):
#     def __init__(self, config_object):
#         self.config = config_object
# 
#     def before_ws_call_prepare_request_kwargs(self, payload):
#         return {
#             "body": self.before_ws_call_transform_payload(payload),
#             "headers": self._get_requests_headers(payload),
#             "auth": self._get_requests_auth(payload),
#             "url": self._get_requests_url(payload),
#         }
# 
#     def before_ws_call_transform_payload(self, payload):
#         return payload
# 
#     def send(self, payload):
#         request_kwargs = self.before_ws_call_prepare_request_kwargs(payload)
#         log.debug(request_kwargs["body"])
#         response = self.send_request(**request_kwargs)
#         log.info("WS response time %s" % response.elapsed.total_seconds())
#         return self.handle_response(response)
# 
#     def _get_requests_headers(self, payload=None):
#         return None
# 
#     def _get_requests_auth(self, payload=None):
#         return None
# 
#     def _get_requests_url(self, payload=None):
#         if self.config.is_test and self.config.ws_test_url:
#             return self.config.ws_test_url
#         return self.config.ws_url
# 
#     def send_request(self, body, url, auth=None, headers=None, method="post", **kwargs):
#         send = getattr(requests, method)
#         return send(url, headers=headers, auth=auth, data=body, **kwargs)
# 
#     @abstractmethod
#     def handle_200(self, response):
#         """
#         Handle response type 200 (success).
#         But it still may contain errors from the carrier webservice.
#         """
#         pass
# 
#     @abstractmethod
#     def handle_500(self, response):
#         """Handle reponse in case of ERROR 500 type."""
#         pass
# 
#     def handle_response(self, response):
#         """Handle response of webservice."""
#         str_status_code = "%s" % response.status_code
#         if hasattr(self, "handle_%d" % response.status_code):
#             handle = getattr(self, "handle_%d" % response.status_code)
#         elif hasattr(self, "handle_%sXX" % str_status_code[0]):
#             handle = getattr(self, "handle_%sXX" % str_status_code[0])
#         else:
#             raise CarrierError(
#                 response,
#                 [
#                     {
#                         "id": None,
#                         "message": ("Unexpected status code from server. " "%s: %s")
#                         % (response.status_code, response.reason),
#                     }
#                 ],
#             )
#         if response.status_code < 200 or response.status_code >= 300:
#             log.warning(
#                 "%s error %d" % (self.config.carrier_type, response.status_code)
#             )
#         return handle(response)
# 
# Path: roulier/ws_tools.py
# def remove_empty_tags(xml, ouput_as_string=True):
#     """Remove empty tags with xslt transformation.
# 
#     param: xml a string or a etree type
#     return: unicode string or lxml.etree._XSLTResultTree
#     """
#     # use Jinja env for getting the path of template file
#     # pkg_resouces may be an alternative, but we already
#     # have Jinja
#     env = Environment(
#         loader=PackageLoader("roulier", "templates"), extensions=["jinja2.ext.with_"]
#     )
#     template = env.get_template("remove_empty_tags.xsl")
#     xsl = etree.parse(open(template.filename))
#     transform = etree.XSLT(xsl)
# 
#     if isinstance(xml, str):
#         xml = etree.fromstring(xml)
#     # else we asume xml is an lxml.etree
#     if ouput_as_string:
#         return str(transform(xml))
#     else:
#         return transform(xml)


from jinja2 import Environment, PackageLoader
from lxml import objectify, etree
from roulier.exception import CarrierError
from roulier.transport import RequestsTransport
from roulier.ws_tools import remove_empty_tags
import logging
"""Implement dpdWS."""




log = logging.getLogger(__name__)


class DpdTransport(RequestsTransport):
    """Implement Dpd WS communication."""

    def before_ws_call_transform_payload(self, payload):
        body = payload["body"]
        headers = payload["headers"]
        soap_message = self.soap_wrap(body, headers)
        log.debug(soap_message)
        return soap_message

    def soap_wrap(self, body, auth):
        """Wrap body in a soap:Enveloppe."""
        env = Environment(
            loader=PackageLoader("roulier", "carriers/dpd_fr_soap/templates"),
            extensions=["jinja2.ext.with_"],
        )

        template = env.get_template("dpd_soap.xml")

# Path: roulier/exception.py
# class CarrierError(Exception):
#     """Error from WS.
# 
#     Use this class in your application to manage
#     exception with the carrier WS
#     """
# 
#     def __init__(self, response, msg=None):
#         if msg is None:
#             msg = "An error occured with WS"
#         super(CarrierError, self).__init__(msg)
#         self.response = response
#         if self.response:
#             if hasattr(self.response, "text"):
#                 log.debug(response.text)
#             else:
#                 log.debug(response)
# 
# Path: roulier/transport.py
# class RequestsTransport(ABC):
#     def __init__(self, config_object):
#         self.config = config_object
# 
#     def before_ws_call_prepare_request_kwargs(self, payload):
#         return {
#             "body": self.before_ws_call_transform_payload(payload),
#             "headers": self._get_requests_headers(payload),
#             "auth": self._get_requests_auth(payload),
#             "url": self._get_requests_url(payload),
#         }
# 
#     def before_ws_call_transform_payload(self, payload):
#         return payload
# 
#     def send(self, payload):
#         request_kwargs = self.before_ws_call_prepare_request_kwargs(payload)
#         log.debug(request_kwargs["body"])
#         response = self.send_request(**request_kwargs)
#         log.info("WS response time %s" % response.elapsed.total_seconds())
#         return self.handle_response(response)
# 
#     def _get_requests_headers(self, payload=None):
#         return None
# 
#     def _get_requests_auth(self, payload=None):
#         return None
# 
#     def _get_requests_url(self, payload=None):
#         if self.config.is_test and self.config.ws_test_url:
#             return self.config.ws_test_url
#         return self.config.ws_url
# 
#     def send_request(self, body, url, auth=None, headers=None, method="post", **kwargs):
#         send = getattr(requests, method)
#         return send(url, headers=headers, auth=auth, data=body, **kwargs)
# 
#     @abstractmethod
#     def handle_200(self, response):
#         """
#         Handle response type 200 (success).
#         But it still may contain errors from the carrier webservice.
#         """
#         pass
# 
#     @abstractmethod
#     def handle_500(self, response):
#         """Handle reponse in case of ERROR 500 type."""
#         pass
# 
#     def handle_response(self, response):
#         """Handle response of webservice."""
#         str_status_code = "%s" % response.status_code
#         if hasattr(self, "handle_%d" % response.status_code):
#             handle = getattr(self, "handle_%d" % response.status_code)
#         elif hasattr(self, "handle_%sXX" % str_status_code[0]):
#             handle = getattr(self, "handle_%sXX" % str_status_code[0])
#         else:
#             raise CarrierError(
#                 response,
#                 [
#                     {
#                         "id": None,
#                         "message": ("Unexpected status code from server. " "%s: %s")
#                         % (response.status_code, response.reason),
#                     }
#                 ],
#             )
#         if response.status_code < 200 or response.status_code >= 300:
#             log.warning(
#                 "%s error %d" % (self.config.carrier_type, response.status_code)
#             )
#         return handle(response)
# 
# Path: roulier/ws_tools.py
# def remove_empty_tags(xml, ouput_as_string=True):
#     """Remove empty tags with xslt transformation.
# 
#     param: xml a string or a etree type
#     return: unicode string or lxml.etree._XSLTResultTree
#     """
#     # use Jinja env for getting the path of template file
#     # pkg_resouces may be an alternative, but we already
#     # have Jinja
#     env = Environment(
#         loader=PackageLoader("roulier", "templates"), extensions=["jinja2.ext.with_"]
#     )
#     template = env.get_template("remove_empty_tags.xsl")
#     xsl = etree.parse(open(template.filename))
#     transform = etree.XSLT(xsl)
# 
#     if isinstance(xml, str):
#         xml = etree.fromstring(xml)
#     # else we asume xml is an lxml.etree
#     if ouput_as_string:
#         return str(transform(xml))
#     else:
#         return transform(xml)


# Path: roulier/carriers/dpd_fr_soap/transport.py
from jinja2 import Environment, PackageLoader
from lxml import objectify, etree
from roulier.exception import CarrierError
from roulier.transport import RequestsTransport
from roulier.ws_tools import remove_empty_tags
import logging

"""Implement dpdWS."""




log = logging.getLogger(__name__)


class DpdTransport(RequestsTransport):
    """Implement Dpd WS communication."""

    def before_ws_call_transform_payload(self, payload):
        body = payload["body"]
        headers = payload["headers"]
        soap_message = self.soap_wrap(body, headers)
        log.debug(soap_message)
        return soap_message

    def soap_wrap(self, body, auth):
        """Wrap body in a soap:Enveloppe."""
        env = Environment(
            loader=PackageLoader("roulier", "carriers/dpd_fr_soap/templates"),
            extensions=["jinja2.ext.with_"],
        )

        template = env.get_template("dpd_soap.xml")

        body_stripped = remove_empty_tags(body)