import json

from django.http import Http404
from django.views.generic.base import View
from django.views.generic.detail import DetailView, SingleObjectMixin

from passerelle import utils

from .models import Bdp

# See documentation:
# https://dev.entrouvert.org/projects/bdp/wiki/WebServices


class ResourcesView(View, SingleObjectMixin):
    model = Bdp

    @utils.protected_api('can_access')
    @utils.to_json()
    def get(self, request, *args, **kwargs):
        text_key = request.GET.get('text_key')
        id_key = request.GET.get('id_key')
        resources = self.get_object().get_api(kwargs['resources'], **(request.GET))
        for r in resources:
            if id_key:
                r['id'] = r[id_key]
            r['id'] = '%s' % r['id']
            if text_key:
                r['text'] = r[text_key]
            elif 'text' not in r:
                r['text'] = r['id']
        return {'data': resources}


class PostAdherentView(View, SingleObjectMixin):
    model = Bdp

    def get(self, request, *args, **kwargs):
        raise Http404

    @utils.protected_api('can_access')
    @utils.to_json()
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)  # JSON w.c.s. formdata
        date_de_naissance = data['fields'].get('date_de_naissance')
        # force 1973-04-18T00:00:00Z
        date_de_naissance = date_de_naissance[:10] + 'T00:00:00Z'
        abonnements = (
            data['fields'].get('abonnements_raw')
            or data['fields'].get('abonnements_raw')
            or request.GET.get('abonnements')
        )
        bibliotheque_id = (
            data['fields'].get('bibliotheque_raw')
            or data['fields'].get('bibliotheque')
            or request.GET.get('bibliotheque')
        )
        adherent = {
            'nom': data['fields'].get('nom'),
            'prenom': data['fields'].get('prenom'),
            'email': data['fields'].get('courriel'),
            'hashpass': data['fields'].get('mot_de_passe').get('cleartext'),
            'dateNaissance': date_de_naissance,
            'actif': 'on',
            'bibliotheque': {'id': bibliotheque_id},
            'abonnements': abonnements,
        }
        return {'data': self.get_object().post_api('adherents', adherent)}


class BdpDetailView(DetailView):
    model = Bdp
    template_name = 'bdp/bdp_detail.html'
