# -*- encoding: utf-8 -*-

from datetime import date, datetime, timedelta       # timeSlices
from collections import OrderedDict
import csv

import django
from django.http import HttpResponse, HttpResponseRedirect
from django.template import Template, RequestContext, loader
from django.shortcuts import render, redirect

from django.contrib.auth.decorators import login_required
from django.urls import reverse  
from django.views.decorators.csrf import ensure_csrf_cookie
from django import forms
from django.forms import ModelForm
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import pgettext, pgettext_lazy

from django.db import transaction
from django.db.models import F

from django.db.models import Count
from django.db.models.functions import TruncMonth
from django.db.models.functions import TruncYear 

from django.core.exceptions import ValidationError

import logging

from django.conf import settings as appSettings

from . import models
from . import forms
from . import auth as nalodeni_auth

# Logger instance
logger = logging.getLogger(__name__)

def role_required(roles=[]):
    def decorate(func):
        def call(request, *args, **kwargs):
            for r in roles:
                if not r in request.session['site_perms']:
                    messages.error(request, "Nedostatečné oprávnění pro přístup. Detaily byly zaznamenány.")
                    return HttpResponseRedirect('/')
            result = func(request, *args, **kwargs)
            return result
        return call
    return decorate

def get_AppUser_objects(request):
    ''' Zkontroluje, že všechny objekty v 'objs' vyhovují přiděleným rolím.
        Nevyhovující vyřadí.
    '''
    sp = request.session['site_perms']
    if 'sso_kodo' not in sp:
        return models.AppUser.objects.none()

    if 'sso_admin' in sp:
        return models.AppUser.objects.all()

    objs = models.AppUser.objects.filter(district__in=request.session['spc']['dist'])

    return objs

def get_AppUser_districts(request):
    '''Vrátí dostupné kraje podle rolí.'''


    if 'sso_admin' in request.session['site_perms']:
        return list(models.AppUser.DISTRICT_CHOICES)

    rslt = []
    for d in models.AppUser.DISTRICT_CHOICES:
        if d[0] in request.session['spc']['dist']:
            rslt.append(d)

    return rslt
    

@ensure_csrf_cookie
@login_required(login_url="/prihlaseni")
@role_required(['sso_kodo'])
def reg_counts(request, dist=None):
    if dist is None:
        dist = int(request.POST.get('dist', -1))

    objs = get_AppUser_objects(request)

    districts = [(-1, ' -- vše dostupné -- ')] + get_AppUser_districts(request)
    # filtrujeme jen povolene kraje, nebo vse pro adminy
    if dist != -1 and (dist in request.session['spc']['dist'] or 'sso_admin' in request.session['site_perms']):
        selDist = dist
        objs = objs.filter(district=selDist)
    else:
        selDist = -1

    objs = objs.annotate( month=TruncMonth('createdStamp')).values('month', 'district').annotate(c=Count('id')).order_by('district','month')

    for o in objs:
        o['district'] = models.AppUser.DISTRICT_CHOICES_STR[o['district']] if o['district'] is not None else "---"
        #print( "%s \t %s \t %s" % (o['district'], o['month'].strftime('%Y-%m'),o['c']))

    template = 'stats/reg_counts.html'
    context = {
        'objs' : objs,
        'distAvail' : districts,
        'selDist' : selDist,
        }

    return render(request, template, context)


