# -*- coding: utf-8 -*-
#
# UnivNautes
# Copyright (C) 2014  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/>.

from django.conf import settings
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import login as django_login
from django.template import Template, Context
import urllib2
from django.http import HttpResponse
from django.shortcuts import redirect
import subprocess

import pfconfigxml

class Homepage(TemplateView):
    '''Homepage View, displays a welcome message'''
    template_name = 'homepage.html'

    def dispatch(self, request, *args, **kwargs):
        pfsenseid = request.session.get('pfsenseid')
        if not pfsenseid:
            return redirect('login')
        if pfsenseid in ('BLACKLISTED'):
            return redirect('logout')
        return super(Homepage, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, *args, **kwargs):
        context = super(Homepage, self).get_context_data(*args, **kwargs)
        url, delay = pfconfigxml.get_redirect_params()
        if url == 'next_url':
            url = self.request.COOKIES.get('next_url', '')
        else:
            url = Template(url).render(Context(context))
        context.update({'redirect_url': url,
                        'redirect_delay': delay})
        return context

homepage = login_required(Homepage.as_view())

def login(request):
    response = django_login(request)
    response.set_cookie('next_url', request.GET.get('next', ''), path='/')
    return response

def proxymap(request, z, x, y):
    tiles_url = pfconfigxml.get_tilesurl() or settings.PROXYMAP_URL
    url = tiles_url % { 'z': int(z), 'x': int(x), 'y': int(y) }
    downstream_request = urllib2.Request(url)
    page = urllib2.urlopen(downstream_request)
    return HttpResponse(page, page.info().getheader('Content-Type'))

def logout(request):
    # 1. disconnect from the captive portal
    cmd = [ c % {
            'cpzone': request.META.get('HTTP_X_PFSENSE_CPZONE') or '',
            'ip': request.META['REMOTE_ADDR'],
            } for c in settings.UNIVNAUTES_CP_DISCONNECT_CMD ]
    p = subprocess.call(cmd)
    # 2. disconnect from django
    return redirect('django_logout_then_login')

