from django.shortcuts import render, resolve_url
from django.http import HttpResponseRedirect, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import views as auth_views
from django.utils.translation import ugettext as _
from django.views.generic import FormView
from mellon.utils import get_idps

from saml.forms import RegistrationForm
from saml.utils import sso_attributes, craft_user_nickname, render_message, \
        ldap_contains_user, generate_eppn, wcs_submit

from saml.views import MSG_USERNONE, wcs_fields, wcs_multiple_fields

import urllib
import logging

logger = logging.getLogger('sp_sso.resource')

@csrf_exempt
def index(request):
    """Main view for the service provider"""
    if request.method != 'GET':
        return HttpResponse('Bad method.', status=405)
    request.session['tracking_code'] = request.GET.get('tracking_code')
    logger.info(request.GET.get('tracking_code'))
    return render(request, 'index.html', locals())

def login(request, *args, **kwargs):
    """Defers the login scheme to the identity provider thanks to mellon"""
    if any(get_idps()):
        if not 'next' in request.GET:
            return HttpResponseRedirect(resolve_url('mellon_login'))
        request.session['next_field'] = request.GET.get('next')
        return HttpResponseRedirect(resolve_url('mellon_login') + '?next='
                                    + urllib.quote(request.GET.get('next')))
    return auth_views.login(request, *args, **kwargs)

def logout(request, next_page=None):
    """Defers the logout scheme to the identity provider thanks to mellon"""
    if any(get_idps()):
        return HttpResponseRedirect(resolve_url('mellon_logout'))
    auth_logout(request)
    next_page = '/login'
    return HttpResponseRedirect(next_page)

def logged_in(request, next_page=None):
    callback = request.session.get('next_field', '/')
    return HttpResponseRedirect(callback)

def subscribed(request):
    """Success view for the self-subscription process"""
    logger.info(u'Processing request %s',  request)
    return render_message(request, _("Subscription request sent."))

class Declare(FormView):
    """Self-subscription FormView

    Users allowed to self-subscribe to the Campus MUSTN'T be registered to the
    Campus LDAP directory yet. (Presence checking is performed against their
    eduPersonPrincipalName).

    Additionnally, their institution (supannEtablissement) or research unit
    (supannEntiteAffectation) MUST be declared in the Campus database.

    These restrictions are processed thanks to the `user_can_declare`
    decorator.

    """
    form_class = RegistrationForm
    template_name = 'declare_form.html'
    success_url = '/declare/subscribed/'

    def get_initial(self):
        initial = super(Declare, self).get_initial()

        if 'mellon_session' in self.request.session:
            data = self.request.session['mellon_session']
            for attribute in sso_attributes:
                if data.get(attribute):
                    attribute_element = data.get(attribute)[0]
                    initial[attribute] = attribute_element
            initial['user_nickname'] = craft_user_nickname(data)
        return initial

    def form_valid(self, form):
        pocform = 'inscription-des-membres'
        wcs = 'http://forms-condorcet.dev.entrouvert.org/'
        posturl = wcs+'/api/formdefs/'+pocform+'/submit'

        post_dict = self.request.POST
        form_adequate_data = {}
        form_adequate_data['ep_principal_name'] = post_dict.get(
            'ep_principal_name')

        if form_adequate_data['ep_principal_name'] \
                and ldap_contains_user(form_adequate_data):
            return render_message(self.request, MSG_USERNONE)
        else:
            delimiter = ','
            wcs_rest_data = {}

            for field in wcs_fields:
                sanitized_form_entry = post_dict.get(field, False)
                wcs_rest_data[field] = sanitized_form_entry

            for multiple_field in wcs_multiple_fields:
                sanitized_form_list = post_dict.getlist(multiple_field, [])
                wcs_rest_data[multiple_field] = delimiter.join(
                    sanitized_form_list)

            if post_dict.get('ep_principal_name', '') == '':
                wcs_rest_data['ep_principal_name'] = generate_eppn(
                        post_dict.get('nom',''))
            if post_dict.get('s_etablissement', '') != '':
                code_etablissement = post_dict['s_etablissement']
                wcs_rest_data['s_etablissement'] = post_dict['s_etablissement_description']
                wcs_rest_data['s_etablissement_raw'] = code_etablissement

            wcs_submit(wcs_rest_data, posturl)
            return super(Declare, self).form_valid(form)

declare = Declare.as_view()
