from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.utils.html import escape
from django.utils.safestring import mark_safe

from storycraft.models import StorycraftGame, StorycraftLine, StorycraftPlayer

def index(request):
    """Display a short list of each game (and its summary) in the system.

    TODO: add paginator.
    """

    games = StorycraftGame.objects.all()
    return render_to_response('storycraft/index.html', {'games': games}, context_instance=RequestContext(request))

def game_index(request, game_id):
    """Display one individual game's details, including the story, if it's done."""

    game = get_object_or_404(StorycraftGame, pk=game_id)
    players = StorycraftPlayer.objects.filter(game=game.id)
    lines = StorycraftLine.objects.filter(game=game.id)
    pretty_story = []

    if game.is_completed():
        # make a HTML-formatted string that is the entire story, in
        # which we've added paragraphs and such.
        period_count = 0
        pretty_story.append('<p>')
        for line in lines:
            period_count = period_count + line.line.count('.')
            if period_count > 6:
                period_count = 0
                split = line.line.rsplit('.', 1)
                pretty_story.append('<span title="' + line.player.nick + ' @ ' + line.time + '">' + escape(split[0]) + '.</span></p>')
                pretty_story.append('<p><span title="' + line.player.nick + ' @ ' + line.time + '">' + escape(split[1]) + '</span>')
            else:
                pretty_story.append('<span title="' + line.player.nick + ' @ ' + line.time + '">' + escape(line.line) + '</span>')
        pretty_story.append('</p>')
    pretty_story_text = ' '.join(pretty_story)
    mark_safe(pretty_story_text)

    return render_to_response('storycraft/game_index.html', {'game': game, 'players': players, 'lines': lines, 'prettystory': pretty_story_text}, context_instance=RequestContext(request))

# vi:tabstop=4:expandtab:autoindent