import json
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic.detail import SingleObjectMixin
from django.views.generic import View, UpdateView, CreateView
from django.contrib.auth.decorators import login_required

# Add library search path entry?
from .utils import get_form_entry, ldap_add_entry, ldap_operation
from .models import LDAPResource, Query
from .forms import QueryForm

#TODO
#   derive csv connector
#   online LDAP query
#   LDIF import
#   server name and credentials sent during the connector creation

CURRENT_CONNECTOR = 'condorcet'

# Create your views here.
def dummy_view(request):
    return HttpResponse("Dummy LDAP connector view.")

#@login_required
def wcs(request, slug="", wcs_entry_id=0):
    json_response = get_form_entry(wcs_entry_id)
    dict = json.loads(json_response)
    #indent = json.dumps(dict, sort_keys=True, indent=4)
    res = ldap_add_entry(dict['fields'])

    if res:
        message = "L'utilisateur a bien ete ajoute a l'annuaire."
    else:
        message = "Erreur lors de l'ajout dans l'annuaire."

    return render(request, 'ldap_dir/simple_message.html', locals())

class LDAPView(View, SingleObjectMixin):
    def get(self, request, *args, **kwargs):
        return HttpResponse("Got the LDAP!")

    def post(self, request, *args, **kwargs):
        return HttpResponse("Got the LDAP!")

class LDAPDownload(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse("FIXME Not implemented yet")

class NewQueryView(CreateView):
    model = Query
    form_class = QueryForm
    template_name = 'ldap_dir/query_form.html'

    def form_valid(self, form):
        query = form.save(commit=False)
        query.resource = LDAPResource.objects.get(slug=CURRENT_CONNECTOR)
        return super(NewQueryView, self).form_valid(form)

    def get(self, request, *args, **kwargs):
        form = self.form_class
        return render(request, self.template_name, locals())

    def post(self, request, *args, **kwargs):
        data = request.POST
        connector = LDAPResource.objects.get(slug=self.kwargs['connector_slug'])
        return HttpResponse(str(ldap_operation(connector, data)))

    def get_context_data(self, **kwargs):
        ctx = super(NewQueryView, self).get_context_data(**kwargs)
        ctx['resource'] = LDAPResource.objects.get(slug=self.kwargs['connector_slug'])
        return ctx

    def get_initial(self):
        initial = super(NewQueryView, self).get_initial()
        initial['resource'] = LDAPResource.objects.get(slug=self.kwargs['connector_slug']).id
        return initial

    def get_success_url(self):
        #return self.object.resource.get_absolute_url()
        return "/" # XXX

class UpdateQueryView(UpdateView):
    model = Query # FIXME not implemented yet
    form_class = QueryForm
    template_name = 'ldap_dir/query_form.html'

    def get_context_data(self, **kwargs):
        ctx = super(UpdateQueryView, self).get_context_data(**kwargs)
        ctx['resource'] = LDAPResource.objects.get(slug=self.kwargs['connector_slug'])
        return ctx

    def get_success_url(self):
        #return self.object.resource.get_absolute_url()
        return "/" # XXX not implemented yet
