import datetime
import djapian
from django.template import RequestContext, loader
from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect
from django.views.generic import list_detail
from django.views.generic.simple import direct_to_template
from django.core.paginator import Paginator
from events.models import ChronokiwiEvent, ChronokiwiChronology, ChronokiwiBaseObject
from events.index import complete_indexer
from django import forms
from django.contrib import admin
import export_to_graphviz
from django.contrib.gis.admin.options import GeoModelAdmin

geomodeladmin_instance = GeoModelAdmin(ChronokiwiBaseObject,admin.site)
ChronokiwiGeometryWidget = geomodeladmin_instance.get_map_widget(ChronokiwiBaseObject._meta.get_field('geometry'))

class ChronokiwiGeoForm(forms.ModelForm):
    geometryWidget = ChronokiwiGeometryWidget()
    geometryWidget.modifiable = False
    geometry = forms.CharField(label='',widget=geometryWidget)
    class Media:
        js = ("http://openlayers.org/api/2.8/OpenLayers.js",)
    class Meta:
        model = ChronokiwiBaseObject
        fields = [ 'geometry' ]

def index(request):
    today_events = ChronokiwiEvent.objects.filter(date=datetime.date.today()).order_by('-lastUpdate')[:4]
    latest_chronologies = ChronokiwiChronology.objects.all().order_by('-lastUpdate')[:20]
    t = loader.get_template('events/index.html')
    c = RequestContext(request, {
        'today_events' : today_events,
        'latest_chronologies': latest_chronologies,
    })
    return HttpResponse(t.render(c))

class SearchForm(forms.Form):
    q = forms.CharField(required=False,label='Search')

def search(request):
    results = []
    if request.GET:
        form = SearchForm(request.GET)
        if form.is_valid():
            query = form.cleaned_data['q']
            paginator = Paginator(complete_indexer.search(query).flags(djapian.resultset.xapian.QueryParser.FLAG_PARTIAL | djapian.resultset.xapian.QueryParser.FLAG_PHRASE ).prefetch(), 20)
            results = paginator.page(int(request.GET.get('page', 1)))
    else:
        form = SearchForm()
    return render_to_response('events/search.html', {'results': results, 'searchForm': form}, RequestContext( request ))
    
def event_list(request):
    return list_detail.object_list( request, queryset= ChronokiwiEvent.objects.all().order_by("-lastUpdate"), paginate_by=20 )

def chronology_list(request):
    return list_detail.object_list( request, queryset= ChronokiwiChronology.objects.all().order_by("-lastUpdate"), paginate_by=20 )
    
def event_detail(request, event_id):
    geoForm = ChronokiwiGeoForm(instance=ChronokiwiEvent.objects.get(pk=event_id))
    return list_detail.object_detail( request, queryset= ChronokiwiEvent.objects.all(), object_id=event_id, extra_context={'geoForm':geoForm} )
    
def chronology_detail(request, chronology_id):
    geoForm = ChronokiwiGeoForm(instance=ChronokiwiChronology.objects.get(pk=chronology_id))
    return list_detail.object_detail( request, queryset= ChronokiwiChronology.objects.all(), object_id=chronology_id, extra_context={'geoForm':geoForm} )
    
def about(request):
    return direct_to_template(request, template='events/about.html')
    
class ChronologiesToExportChoiceField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return obj.name

class ExportForm(forms.Form):
    chronologies = ChronologiesToExportChoiceField(required=True,label='Chronologies',queryset=ChronokiwiChronology.objects.all())
    format = forms.ChoiceField(required=True,label='Format',choices=[('graphviz','graphviz'),('graphviz_jpg','graphviz jpg')],initial='graphviz')
    
def export(request):
    textFileContent = None
    imageUrl = None
    if request.GET:
        form = ExportForm(request.GET)
        if form.is_valid():
            chronologies = form.cleaned_data['chronologies']
            print( 'prout' + str( chronologies ) )
            format = form.cleaned_data['format']
            if format == 'graphviz':
                textFileContent = export_to_graphviz.export_to_dot( chronologies )
            elif format == 'graphviz_jpg':
                imageUrl = export_to_graphviz.export_to_jpg(chronologies)
    else:
        form = ExportForm()
    return render_to_response('events/export.html', {'exportForm': form, 'textFileContent': textFileContent, 'imageUrl' : imageUrl}, RequestContext( request ))