# -*- coding: utf-8 -*-
#
# ITerativ GmbH
# http://www.iterativ.ch/
#
# Copyright (c) 2013 ITerativ GmbH. All rights reserved.
#
# Created on Nov 28, 2013
# @author: maersu <me@maersu.ch>
import datetime
from django import forms
from modeltimeline.utils import TimeLiner, DataFilterConfig, TL_ICON_FONT_CSS_URL, TL_DEFAULT_DAYS_FORWARD, \
    TL_DEFAULT_DAYS_BACKWARD
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.contrib.admin.models import LogEntry


class DateForm(forms.Form):
    start = forms.DateField(initial=datetime.date.today() + datetime.timedelta(days=-TL_DEFAULT_DAYS_BACKWARD))
    end = forms.DateField(initial=datetime.date.today() + datetime.timedelta(days=TL_DEFAULT_DAYS_FORWARD))


class TimeLine(TemplateView):
    template_name = 'timeline/index.html'
    template_name_content = 'timeline/content.html'

    track_models = [
        {'model': User, 'icon-class': 'user', 'fields': ['date_joined']},
        {'model': LogEntry, 'icon-class': 'log_book', 'fields': ['action_time'], 'checked': False}
    ]

    def __init__(self, **kwargs):
        super(TimeLine, self).__init__(**kwargs)

    def is_get_content(self):
        return self.request.GET.has_key('content')

    def get_context_data(self):
        context = super(TimeLine, self).get_context_data()

        if self.is_get_content():
            return self.get_context_data_content(context)

        return self.get_context_data_index(context)

    def get_template_names(self):

        if self.is_get_content():
            return [self.template_name_content]

        return [self.template_name]

    def get_context_data_index(self, context):
        used_timeline_filters = self.request.session.get('used_timeline_filters', None)

        context['config'] = DataFilterConfig(self.track_models, used_timeline_filters)
        context['TL_ICON_FONT_CSS_URL'] = TL_ICON_FONT_CSS_URL
        context['form'] = DateForm()
        return context

    def get_context_data_content(self, context):
        get = self.request.GET.copy()

        dc = DataFilterConfig(self.track_models)

        form = DateForm(self.request.GET)

        if not form.is_valid():
            context['errors'] = form.errors
            return context

        filters = get.getlist('filters[]')
        tl = TimeLiner(form.cleaned_data['start'], form.cleaned_data['end'])

        for f in dc:
            if f['class_name'] in filters:
                tl.add_time_stamped(f['model'], fields=f['fields'], icon=f['icon-class'])

        tl.initialize()
        context['timeliner'] = tl

        self.request.session['used_timeline_filters'] = filters

        return context