# bijoe - BI dashboard
# 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
import urllib

from django.shortcuts import resolve_url
from django.core.urlresolvers import reverse
from django.views.generic import TemplateView, View
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.translation import ugettext as _
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import views as auth_views
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import PermissionDenied

try:
    from mellon.utils import get_idps
except ImportError:
    get_idps = lambda: []

from .utils import get_warehouses
from .engine import Engine
from .visualization.models import Visualization


class AuthorizationMixin(object):
    def authorize(self, request):
        if request.user.is_authenticated():
            if not request.user.is_superuser:
                raise PermissionDenied(_('You must be superuser'))
            return True
        else:
            return False

    def dispatch(self, request, *args, **kwargs):
        if self.authorize(request):
            return super(AuthorizationMixin, self).dispatch(request, *args, **kwargs)
        else:
            return redirect_to_login(request.build_absolute_uri())


class HomepageView(AuthorizationMixin, TemplateView):
    template_name = 'bijoe/homepage.html'

    def get_context_data(self, **kwargs):
        ctx = super(HomepageView, self).get_context_data(**kwargs)
        ctx['visualizations'] = Visualization.objects.all()
        ctx['warehouses'] = sorted((Engine(w) for w in get_warehouses(self.request)),
                                   key=lambda w: w.label)
        return ctx

    def get(self, request, *args, **kwargs):
        ctx = self.get_context_data()
        if not len(ctx['visualizations']) and len(ctx['warehouses']) == 1:
            return HttpResponseRedirect(reverse('warehouse', kwargs={'warehouse': ctx['warehouses'][0].name}),
                                        status=307)
        return super(HomepageView, self).get(request, *args, **kwargs)


class MenuJSONView(AuthorizationMixin, View):
    def get(self, request, *args, **kwargs):
        response = HttpResponse(content_type='application/json')
        menu = [
            {
                'label': _('Statistics'),
                'slug': 'statistics',
                'url': request.build_absolute_uri(reverse('homepage')),
            }
        ]
        json_str = json.dumps(menu)
        for variable in ('jsonpCallback', 'callback'):
            if variable in request.GET:
                response = HttpResponse(content_type='application/javascript')
                json_str = '%s(%s);' % (request.GET[variable], json_str)
                break
        response.write(json_str)
        return response


homepage = HomepageView.as_view()
menu_json = MenuJSONView.as_view()


def login(request, *args, **kwargs):
    if any(get_idps()):
        if not 'next' in request.GET:
            return HttpResponseRedirect(resolve_url('mellon_login'))
        return HttpResponseRedirect(resolve_url('mellon_login') + '?next='
                                    + urllib.quote(request.GET.get('next')))
    return auth_views.login(request, template_name='bijoe/login.html')


def logout(request, next_page=None):
    if any(get_idps()):
        return HttpResponseRedirect(resolve_url('mellon_logout'))
    auth_logout(request)
    if next_page is not None:
        next_page = resolve_url(next_page)
    else:
        next_page = '/'
    return HttpResponseRedirect(next_page, template_name='bijoe/logged_out.html')
