import urlparse

from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.utils.translation import ugettext as _
try:
    from django.utils.timezone import now   # Django 1.4 aware datetimes
except ImportError:
    from datetime import datetime
    now = datetime.now

from postman.fields import autocompleter_app
from postman.forms import WriteForm, AnonymousWriteForm, QuickReplyForm, FullReplyForm
from postman.models import Message, get_order_by
from postman.urls import OPTION_MESSAGES
from postman.utils import format_subject, format_body


##########
# Helpers
##########
def _get_referer(request):
    """Return the HTTP_REFERER, if existing."""
    if 'HTTP_REFERER' in request.META:
        sr = urlparse.urlsplit(request.META['HTTP_REFERER'])
        return urlparse.urlunsplit(('', '', sr.path, sr.query, sr.fragment))


########
# Views
########
def _folder(request, folder_name, view_name, option, template_name):
    """Code common to the folders."""
    kwargs = {}
    if option:
        kwargs.update(option=option)
    order_by = get_order_by(request.GET)
    if order_by:
        kwargs.update(order_by=order_by)
    msgs = getattr(Message.objects, folder_name)(request.user, **kwargs)
    return render_to_response(template_name, {
        'pm_messages': msgs,    # avoid 'messages', already used by contrib.messages
        'by_conversation': option is None,
        'by_message': option == OPTION_MESSAGES,
        'by_conversation_url': reverse(view_name),
        'by_message_url': reverse(view_name, args=[OPTION_MESSAGES]),
        'current_url': request.get_full_path(),
        'gets': request.GET,  # useful to postman_order_by template tag
        }, context_instance=RequestContext(request))


@login_required
def inbox(request, option=None, template_name='postman/inbox.html'):
    """
    Display the list of received messages for the current user.

    Optional arguments:
        ``option``: display option:
            OPTION_MESSAGES to view all messages
            default to None to view only the last message for each conversation
        ``template_name``: the name of the template to use

    """
    return _folder(request, 'inbox', 'postman_inbox', option, template_name)


@login_required
def sent(request, option=None, template_name='postman/sent.html'):
    """
    Display the list of sent messages for the current user.

    Optional arguments: refer to inbox()

    """
    return _folder(request, 'sent', 'postman_sent', option, template_name)


@login_required
def archives(request, option=None, template_name='postman/archives.html'):
    """
    Display the list of archived messages for the current user.

    Optional arguments: refer to inbox()

    """
    return _folder(request, 'archives', 'postman_archives', option, template_name)


@login_required
def trash(request, option=None, template_name='postman/trash.html'):
    """
    Display the list of deleted messages for the current user.

    Optional arguments: refer to inbox()

    """
    return _folder(request, 'trash', 'postman_trash', option, template_name)


def write(request, recipients=None, form_classes=(WriteForm, AnonymousWriteForm),
          autocomplete_channels=None, template_name='postman/write.html',
          success_url=None, user_filter=None, exchange_filter=None,
          max=None, auto_moderators=[]):
    """
    Display a form to compose a message.