# passerelle.contrib.sve_by_email
# 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

import requests
try:
    import cStringIO as StringIO
except ImportError:
    import StringIO

from django.conf import settings

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


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
        if getattr(settings, 'REQUESTS_PROXIES', None):
            kwargs['proxies'] = settings.REQUESTS_PROXIES
        return kwargs

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

    def send(self, request):
        self.addcredentials(request)
        resp = 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 client_to_jsondict(client):
    """return description of the client, as dict (for json export)"""
    res = {}
    for i, sd in enumerate(client.sd):
        d = {}
        d['tns'] = sd.wsdl.tns[1]
        d['prefixes'] = dict(p for p in sd.prefixes)
        d['ports'] = {}
        for p in sd.ports:
            d['ports'][p[0].name] = {}
            for m in p[1]:
                d['ports'][p[0].name][m[0]] = dict(
                        (mp[0], sd.xlate(mp[1])) for mp in m[1])
        d['types'] = {}
        for t in sd.types:
            ft = client.factory.create(sd.xlate(t[0]))
            d['types'][sd.xlate(t[0])] = unicode(ft)
        res[sd.service.name] = d
    return res

def recursive_asdict(d):
    """Convert Suds object into serializable format."""
    out = {}
    for k, v in asdict(d).iteritems():
        if hasattr(v, '__keylist__'):
            out[k] = recursive_asdict(v)
        elif isinstance(v, list):
            out[k] = []
            for item in v:
                if hasattr(item, '__keylist__'):
                    out[k].append(recursive_asdict(item))
                else:
                    out[k].append(item)
        else:
            out[k] = v
    return out
