# -*- coding: utf-8 -*-

import datetime

from django.http import JsonResponse
from django.shortcuts import render
from django.utils import timezone

from .constants import INCOMING_DATE_FORMAT

from .helpers import (
    compute_average_usage_time, count_actual_sessions, count_actual_trainees,
    count_cms_connections, count_document_downloads, count_registrations,
    session_stats_by_trainer, session_stats_by_group_type,
)

from mtp.apps.accounts.models import GroupType
from mtp.apps.trainings.models import Training


def analytics(request):
    """
    Render the basic analytics view.

    The actual data are loaded via an Ajax call to the ``compute_analytics``
    view below.

    """

    trainings = Training.objects.filter(is_deleted=False)
    if not request.user.is_superuser:
        trainings = trainings.filter(public=True)

    context = {
        'current': 'extra_analytics',
        'trainings': trainings
    }

    return render(
        request=request,
        template_name='stats/analytics.html',
        context=context,
    )


def compute_analytics(request):

    # Extract filter data from GET parameters

    date_begin = timezone.datetime.strptime(
        request.GET.get('dateStart'), INCOMING_DATE_FORMAT
    )
    date_end = timezone.datetime.strptime(
        request.GET.get('dateEnd'), INCOMING_DATE_FORMAT
    ) + datetime.timedelta(days=1)
    trainer_id = request.GET.get('trainerId', None)
    training_id = request.GET.get('trainingId', None)

    # Fetch the group type upon which to filter the stats ("CFR" for Renault)

    try:
        group_type_id = GroupType.objects.filter(is_stats_filter=True)[0].pk
    except IndexError:
        group_type_id = None

    # Build statistics as required

    data = {

        'stats': {

            'connections': count_cms_connections(
                date_begin, date_end
            ),
            'users': count_registrations(
                date_begin, date_end
            ),
            'downloaded_files': count_document_downloads(
                date_begin, date_end
            ),
            'sessions': count_actual_sessions(
                date_begin, date_end, training_id, trainer_id
            ),
            'trained_students': count_actual_trainees(
                date_begin, date_end, training_id, trainer_id
            ),
            'session_durations': compute_average_usage_time(
                date_begin, date_end, training_id, trainer_id
            ),

            'trainer_list': session_stats_by_trainer(
                date_begin, date_end, training_id,
            ),

            'group_list': session_stats_by_group_type(
                date_begin, date_end, training_id, group_type_id,
            ),

            # TODO
            'survey_results': [
                {'date': '01/01/2010', 'num_event': '314'},
                {'date': '02/01/2010', 'num_event': '159'},
                {'date': '03/01/2010', 'num_event': '265'}
            ],

        }

    }

    return JsonResponse(data)


##############################################################################
##############################################################################
##############################################################################

def stats(request):
    """ Not sure this is actually still used, but whatever. """

    # FIXME: This should be a setting somewhere.
    f = open('/var/www/mtp/log/youpla.access.log')

    download_line = []
    connect_line = []
    for line in f:
        if 'GET /media/documents/' in line and 'HTTP/1.1 200' in line:
            download_line.append(line)
        if '/accounts/login/?next=/' in line:
            connect_line.append(line)

    month = []
    download_month = {}
    for line in download_line:
        ip, end = line.split(' - - ', 1)
        datestr = end.split('[')[1].split(']')[0].split()[0]
        d = datetime.datetime.strptime(datestr, '%d/%b/%Y:%H:%M:%S')
        if not d.strftime('%b %Y') in month:
            month.append(d.strftime('%b %Y'))
        month_index = month.index(d.strftime('%b %Y'))
        if month_index not in download_month:
            download_month[month_index] = 1
        else:
            download_month[month_index] = download_month[month_index] + 1

    ip_e = []
    connect_month = {}
    for line in connect_line:
        ip, end = line.split(' - - ', 1)
        if ip not in ip_e:
            ip_e.append(ip)
            datestr = end.split('[')[1].split(']')[0].split()[0]
            d = datetime.datetime.strptime(datestr, '%d/%b/%Y:%H:%M:%S')
            if not d.strftime('%b %Y') in month:
                month.append(d.strftime('%b %Y'))
            month_index = month.index(d.strftime('%b %Y'))
            if month_index not in connect_month:
                connect_month[month_index] = 1
            else:
                connect_month[month_index] = connect_month[month_index] + 1

    final_stat = []
    for m in month:
        index = month.index(m)
        final_stat.append([m, download_month[index], connect_month[index]])

    return render(
        request=request,
        template_name='stats/stats.html',
        context=locals(),  # from dimitri with love
    )

    # FIXME: Commenting this code out since it seems to be unreachable anyway.

    # len_ip_e = len(ip_e)
    # len_dowload_line = len(download_line)

    # return HttpResponse(
    #     u'<h1>Statistiques d'utilisation de l'extranet</h1>'
    #     u'<h4>Octobre 2013</h4>'
    #     u'<ul>'
    #     u'<li>Nombre de connexions à l'interface: %d</li>'
    #     u'<li>Nombre de document téléchargés: %d</li>'
    #     u'</ul>' % (
    #         len(ip_e),
    #         len(download_line)
    #     )
    # )
