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

import json

from django.views.generic import DetailView as GenericDetailView
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

from passerelle import utils

from .soap import get_client, client_to_jsondict, recursive_asdict
from .models import SeisinByEmailManagement


class SeisinByEmailManagementDetailView(GenericDetailView):
    model = SeisinByEmailManagement
    template_name = 'passerelle/contrib/seisin_by_email/detail.html'


class DetailView(GenericDetailView):
    model = SeisinByEmailManagement

    def get_client(self):
        return get_client(self.get_object())

    def get_data(self, request, *args, **kwargs):
        raise NotImplementedError

    @utils.protected_api('can_access')
    def get(self, request, *args, **kwargs):
        data = self.get_data(request, *args, **kwargs)
        return utils.response_for_json(request, data)


class PingView(DetailView):
    def get_data(self, request, *args, **kwargs):
        client = self.get_client()
        res = {'ping': 'pong'}
        if 'debug' in request.GET:
            res['client'] = client_to_jsondict(client)
        return res


class ResourceView(DetailView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(ResourceView, self).dispatch(*args, **kwargs)

    @utils.protected_api('can_access')
    def post(self, request, *args, **kwargs):
        client = self.get_client()
        formdata = json.loads(request.body)
        fields = formdata.get('fields', {})
        extras = formdata.get('extra', {})

        debug = 'debug' in request.GET
        if debug:
            debug_output = {}

        # attachment: only one (the first)
        attachmentData = client.factory.create('arrayOfAttachmentContent')
        attachmentData.source = '?'
        for name, value in fields.items():
            if isinstance(value, dict) and value.get('filename') and value.get('content'):
                attachmentData.fileName = '"%s"' % value['filename']
                attachmentData.attachmentType = value.get('content_type')
                attachmentData.source = value['content']
                break

        if debug:
            debug_output['attachmentData'] = '%r' % attachmentData

        # data
        data = client.factory.create('listOfData')
        data.datas = []
        for name, value in extras.items():
            if not name.startswith('seisin_by_email_data_'):
                continue
            item = client.factory.create('arrayOfDataContent')
            item.key = name[21:]
            item.value = value
            data.datas.append(item)

        if debug:
            debug_output['data'] = '%r' % data

        # other variables
        departement_number = extras.get('seisin_by_email_departement_number', '')
        target_entity = extras.get('seisin_by_email_target_entity', -1)
        theme = extras.get('seisin_by_email_theme', '')
        userType = extras.get('seisin_by_email_userType', '')
        request_object = extras.get('seisin_by_email_request_object', '')

        if debug:
            debug_output['departement_number'] = departement_number
            debug_output['target_entity'] = target_entity
            debug_output['theme'] = theme
            debug_output['userType'] = userType
            debug_output['request_object'] = request_object

        # call sendSeisinByEmail web service
        results = client.service.sendSeisinByEmail(departement_number,
                                                   target_entity,
                                                   theme,
                                                   userType,
                                                   request_object,
                                                   data,
                                                   attachmentData)
        data = recursive_asdict(results)

        if debug:
            data['debug'] = debug_output

        return utils.response_for_json(request, data)
