# Copyright (C) 2016  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/>.

import requests
import json
from suds.transport.http import HttpAuthenticated
from suds.client import Client
from suds.transport import Reply
import suds.sudsobject

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache

from passerelle.base.models import BaseResource
from passerelle.utils.api import endpoint
from passerelle.utils.jsonresponse import APIError

from .formdata import FormData, CREATION_SCHEMA, list_schema_fields


class ParameterTypeError(Exception):
    http_status = 400
    log_error = False


def fill_sudsobject_with_dict(sudsobject, fields, prefix=None):
    for key, value in sudsobject:
        if prefix:
            attr = '%s_%s' % (prefix, key)
        else:
            attr = key
        if isinstance(value, suds.sudsobject.Object):
            fill_sudsobject_with_dict(value, fields, attr)
        else:
            if attr in fields:
                # sudsobject.foo.bar <- fields['foo_bar']
                setattr(sudsobject, key, fields[attr])

def sudsobject_to_dict(sudsobject):
    out = {}
    for key, value in suds.sudsobject.asdict(sudsobject).iteritems():
        if hasattr(value, '__keylist__'):
            out[key] = sudsobject_to_dict(value)
        elif isinstance(value, list):
            out[key] = []
            for item in value:
                if hasattr(item, '__keylist__'):
                    out[key].append(sudsobject_to_dict(item))
                else:
                    out[key].append(item)
        else:
            out[key] = value
    return out


class Greco(BaseResource):
    application = models.CharField(_('Application identifier'), max_length=200)
    token_url = models.URLField(_('Token URL'), max_length=256)
    token_authorization = models.CharField(_('Token Authorization'), max_length=128)
    wsdl_url = models.CharField(_('WSDL URL'), max_length=256) # not URLField, it can be file://
    verify_cert = models.BooleanField(default=True,
                                      verbose_name=_('Check HTTPS Certificate validity'))

    category = _('Business Process Connectors')

    class Meta:
        verbose_name = _('GRECO Webservices')

    @classmethod
    def get_icon_class(cls):
        return 'ressources'


    def get_token(self, renew=False):
        cache_key = 'greco-%s-token' % self.id
        if not renew:
            token = cache.get(cache_key)
            if token:
                return token
        headers = {'Authorization': 'Basic %s' % self.token_authorization}
        resp = self.requests.post(self.token_url, headers=headers,
                                  data={'grant_type': 'client_credentials'},
                                  verify=self.verify_cert).json()
        token = '%s %s' % (resp.get('token_type'), resp.get('access_token'))
        timeout = int(resp.get('expires_in'))
        cache.set(cache_key, token, timeout)
        self.logger.debug('new token: %s (timeout %ss)', token, timeout)
        return token

    def get_client(self):
        class Transport(HttpAuthenticated):
            def __init__(self, instance):
                self.instance = instance
                HttpAuthenticated.__init__(self)

            def send(self, request):
                request.message = request.message.replace("contentType", "xm:contentType")
                request.headers['Authorization'] = self.instance.get_token()
                resp = self.instance.requests.post(request.url, data=request.message,
                                                   headers=request.headers,
                                                   verify=self.instance.verify_cert)
                if resp.status_code == 401:
                    # ask for a new token, and retry
                    request.headers['Authorization'] = self.instance.get_token(renew=True)
                    resp = self.instance.requests.post(request.url, data=request.message,
                                                       headers=request.headers,
                                                       verify=self.instance.verify_cert)
                return Reply(resp.status_code, resp.headers, resp.content)

        return Client(url=self.wsdl_url, transport=Transport(self))


    @endpoint(serializer_type='json-api', perm='can_access')
    def ping(self, request):
        return self.get_client().service.communicationTest('ping')

    @endpoint(serializer_type='json-api', perm='can_access', methods=['post'])
    def create(self, request):
        # get creation fields from payload
        try:
            formdata = FormData(json.loads(request.body), CREATION_SCHEMA)
        except ValueError as e:
            raise ParameterTypeError(e.message)
        # create suds object from formdata
        client = self.get_client()
        creation = client.factory.create('DemandeCreation')
        creation.application = self.application
        fill_sudsobject_with_dict(creation, formdata.fields)
        # send it to "creer"
        resp = client.service.creer(creation)
        return sudsobject_to_dict(resp)

    @classmethod
    def creation_fields(cls):
        '''used in greco_detail.html template'''
        return list_schema_fields(CREATION_SCHEMA)

    @endpoint(serializer_type='json-api', perm='can_access')
    def status(self, request, iddemande, idgreco):
        resp = self.get_client().service.consulter({
            'idgreco': idgreco,
            'iddemande': iddemande,
        })
        return sudsobject_to_dict(resp)

    @endpoint(name='add-information', serializer_type='json-api', perm='can_access',
              methods=['get', 'post', 'put', 'patch'])
    def add_information(self, request, iddemande=None, idgreco=None, information=None):
        if request.body:
            payload = json.loads(request.body)
            if not isinstance(payload, dict):
                raise ParameterTypeError('payload must be a dict')
            idgreco = payload.get('idgreco') or idgreco
            iddemande = payload.get('iddemande') or iddemande
            information = payload.get('information') or information
        resp = self.get_client().service.ajouterComplementInformation({
            'idgreco': idgreco,
            'iddemande': iddemande,
            'complementInfo': information,
        })
        return sudsobject_to_dict(resp)

    @endpoint(serializer_type='json-api', perm='can_access',
              methods=['get', 'post', 'put', 'patch'])
    def update(self, request, iddemande=None, idgreco=None, comment=None):
        if request.body:
            payload = json.loads(request.body)
            if not isinstance(payload, dict):
                raise ParameterTypeError('payload must be a dict')
            idgreco = payload.get('idgreco') or idgreco
            iddemande = payload.get('iddemande') or iddemande
            comment = payload.get('comment') or comment
        resp = self.get_client().service.relancer({
            'idgreco': idgreco,
            'iddemande': iddemande,
            'commentaire': comment,
        })
        return sudsobject_to_dict(resp)
