"""This module contains the views of the ``cms`` app"""

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic import View

from mtp.apps.sync.models import LocalServer


@login_required
def index(request):
    current = 'extra_index'
    localservers = LocalServer.objects.exclude(name='').order_by('name')

    # FIXME: This view currently generates 291 database queries for the Renault DB.
    # This is not acceptable. We should probably optimize that with a `select_related()`
    # call.

    return render_to_response('index.html',
        locals(), context_instance=RequestContext(request))


class LastIpaVersion(View):
    """View to redirect the user to the last available IPA version"""

    def get(self, request, *args, **kwargs):  # pylint: disable=unused-argument
        """Build the last IPA url and issue a redirect to it

        Returns
        -------
        HttpResponse

        """

        url = settings.LAST_IPA_VERSION_DETAIL_URL

        response = HttpResponse('', status=302)
        response['Location'] = url

        return response

