# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2015  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# borrowed from https://pypi.python.org/pypi/suds_requests
# and https://docs.oracle.com/cd/E50245_01/E50253/html/vmprg-soap-example-authentication-python.html

from io import BytesIO

from suds.client import Client
from suds.transport import Reply
from suds.transport.http import HttpAuthenticated


class Transport(HttpAuthenticated):
    def __init__(self, model, **kwargs):
        self.model = model
        HttpAuthenticated.__init__(self, **kwargs)  # oldstyle class...

    def get_requests_kwargs(self):
        kwargs = {}
        if self.model.username:
            kwargs['auth'] = (self.model.username, self.model.password)
        if self.model.keystore:
            kwargs['cert'] = (self.model.keystore.path, self.model.keystore.path)
        if not self.model.verify_cert:
            kwargs['verify'] = False
        return kwargs

    def open(self, request):
        resp = self.model.requests.get(request.url, headers=request.headers, **self.get_requests_kwargs())
        return BytesIO(resp.content)

    def send(self, request):
        self.addcredentials(request)
        resp = self.model.requests.post(
            request.url, data=request.message, headers=request.headers, **self.get_requests_kwargs()
        )
        result = Reply(resp.status_code, resp.headers, resp.content)
        return result


def get_client(model):
    transport = Transport(model)
    return Client(model.wsdl_url, transport=transport, cache=None)


def xml_to_dict(result):
    """Converts AXEL simple XML responses into dict()"""
    d = {}
    for child in result:
        d[child.tag.lower()] = xml_to_dict(child)
    if not d:
        return result.text
    return d
