import logging
from datetime import datetime, timedelta

from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404, render_to_response
from django.template.context import RequestContext

from darkroom.models import Webcam
from newsroom.models import (
    ArchiveItem,
    ArchiveSection,
    Author,
    Editorial,
    Story,
    WebEdition
)

logger = logging.getLogger(__name__)


def index(request):
    stories = Story.objects.filter(published=True, published_on__lte=datetime.now)[:9]
    return render_to_response(
        "newsroom/index.html", locals(), context_instance=RequestContext(request)
    )


def archive_index(request):
    archives = ArchiveItem.objects.all().order_by("-modified")
    return render_to_response(
        "newsroom/archive_index.html",
        locals(),
        context_instance=RequestContext(request),
    )


def archive_year(request, year):
    archives = ArchiveItem.objects.filter(published_on__year=year)
    return render_to_response(
        "newsroom/archive_year.html", locals(), context_instance=RequestContext(request)
    )


def archive_detail(request, year, slug):
    archive = get_object_or_404(ArchiveSection, slug=slug)
    return render_to_response(
        "newsroom/archive_detail.html",
        locals(),
        context_instance=RequestContext(request),
    )


def author_list(request):
    authors = Author.objects.all()
    return render_to_response(
        "newsroom/author_list.html", locals(), context_instance=RequestContext(request)
    )


def author_detail(request, type_slug, slug):
    author = Author.objects.get(slug=slug)
    stories = Story.objects.filter(published=True, authors=author)
    return render_to_response(
        "newsroom/author_detail.html",
        locals(),
        context_instance=RequestContext(request),
    )


def update_view_count(request, story):
    """Take a story and a request and check the user agent against an exclusion file.
       By default, if no exclusion file has been set we just increment the view."""
    if not request.excluded_ip:
        story.view_count += 1
        story.save()


def story_detail(request, year, month, day, slug):
    try:
        object = Story.objects.get(slug=slug)
        update_view_count(request, object)
    except Story.DoesNotExist:
        raise Http404
    return render_to_response(
        "newsroom/story_detail.html", locals(), context_instance=RequestContext(request)
    )


def story_old_redirect(request, year, monthdayyear, mangled_slug):
    paper = mangled_slug[0:2]
    mangled_slug.remove(mangled_slug[0])
    mangled_slug.remove(mangled_slug[-1])
    slug = "-".join(mangled_slug)
    try:
        object = Story.objects.get(
            slug=slug, published_on__year=year, published_on__month=monthdayyear[0:2]
        )
        update_view_count(request, object)
    except Story.DoesNotExist:
        raise Http404
    return render_to_response(
        "newsroom/story_detail.html", locals(), context_instance=RequestContext(request)
    )


def editorial_detail(request, year, month, day, slug):
    try:
        object = Editorial.objects.get(slug=slug)
        update_view_count(request, object)
    except Editorial.DoesNotExist:
        raise Http404
    return render_to_response(
        "newsroom/editorial_detail.html",
        locals(),
        context_instance=RequestContext(request),
    )


def tag_index(request):
    tags = Tag.objects.all()
    if request.GET:
        for name in request.GET["filter"].split("+"):
            qs.append(Q(tags__name=name))
        import operator

        stories = Story.objects.filter(reduce(operator.or_, qs))
    return render_to_response(
        "newsroom/tag_index.html", locals(), context_instance=RequestContext(request)
    )


def tag_detail(request, name):
    tag = get_object_or_404(Tag, name=name)
    stories = Story.objects.filter(tags__name=name)
    qs = []
    if request.GET:
        filter_list = request.GET["filter"].split("+")
        for name in filter_list:
            qs.append(Q(tags__name=name))
        import operator

        stories = stories.filter(reduce(operator.or_, qs))
    return render_to_response(
        "newsroom/tag_detail.html", locals(), context_instance=RequestContext(request)
    )


def paper_index(request):
    """
      This view is awful. Hardcoded site ids for the various products. 
      Really, its just part of a scaffold built around our previous 
      site structure for transitional reasons.
    """
    webcams = Webcam.objects.all()

    edition = WebEdition.objects.published().latest()
    prev_edition = (
        WebEdition.objects.published()
        .filter(published_on__lt=edition.published_on)
        .latest()
    )
    other_editions = WebEdition.objects.filter(
        published_on=edition.published_on
    ).exclude(paper=edition.paper)
    prev_other_editions = WebEdition.objects.filter(
        published_on=prev_edition.published_on
    ).exclude(paper=edition.paper)

    latest_editions = WebEdition.objects.published().filter(
        published_on__gte=datetime.now() - timedelta(weeks=2)
    )
    latest_other_editions = WebEdition.objects.filter(
        published_on__gte=datetime.now() - timedelta(weeks=2)
    ).exclude(paper=edition.paper)

    return render_to_response(
        "newsroom/index.html", locals(), context_instance=RequestContext(request)
    )
