#!/usr/bin/env python

"""Additional URL/View routing for URL patterns and views

Django matches URL patterns based solely on pattern (not on pattern and HTTP
Verb). Other frameworks match on both.

In order to follow a more traditional convention as seen in other frameworks,
these methods will additionally route via the HTTP Verb.

For example, the index() and the create() 'actions' that are convention in
other frameworks have the same Django URL pattern. However, the GET requests
are routed to index() and POST requests are routed to create().
"""

from django import http

from blog import views


def index_create(request):

    """This meta-view handles index/create second level routing

    GET    /blog             -> blog.views.index
    POST   /blog             -> blog.views.create

    See also the blog.routes module documentation (above)
    """

    if request.method == "GET":
        return views.index(request)

    if request.method == "POST":
        return views.create(request)

    return http.HttpResponseNotFound(
        '<h1>This is not a route for HTTP verb {0}</h1>'.format(
            request.method))


def show_update_destroy(request, slug):

    """This meta-view handles show/update/destroy second level routing

    GET    /blog/<slug>      -> blog.views.show
    PUT    /blog/<slug>      -> blog.views.update
    DELETE /blog/<slug>      -> blog.views.destroy

    See also the blog.routes module documentation (above)
    """
    # Look for overloaded POSTS first
    if request.method == "POST":
        _method = request.POST.get("_method", None)
        if _method is not None:
            setattr(request, _method, request.POST)
            request.method = _method

    if request.method == "GET":
        return views.show(request, slug)

    if request.method == "PUT":
        return views.update(request, slug)

    if request.method == "DELETE":
        return views.destroy(request, slug)

    return http.HttpResponseNotFound(
        '<h1>This is not a route for HTTP verb {0}</h1>'.format(
            request.method))


def new(request):

    """This meta-view handles new second level routing

    GET    /blog/new         -> blog.views.new

    See the blog.routes module documentation (above)
    """

    if request.method == "GET":
        return views.new(request)

    return http.HttpResponseNotFound(
        '<h1>This is not a route for HTTP verb {0}</h1>'.format(
            request.method))


def edit(request, slug):

    """This meta-view handles new second level routing

    GET    /blog/<slug>/edit -> blog.views.edit

    See the blog.routes module documentation (above)
    """

    if request.method == "GET":
        return views.edit(request, slug)

    return http.HttpResponseNotFound(
        '<h1>This is not a route for HTTP verb {0}</h1>'.format(
            request.method))
