from datetime import date, timedelta
import uuid
from pyramid.security import authenticated_userid

from pyramid.view import view_config
from brewman import groupfinder
from brewman.models.auth import Role, User

def session_current_date(request):
    session = request.session
    if 'currentDate' not in session:
        session['currentDate'] = date.today().strftime('%d-%b-%Y')
    return session['currentDate']

def session_current_date_set(request, date):
    session = request.session
    session['currentDate'] = date
    return session['currentDate']

def session_period_start(request):
    session = request.session
    if 'periodStart' not in session:
        session['periodStart'] = get_first_day(date.today()).strftime('%d-%b-%Y')
    return session['periodStart']


def session_period_finish(request):
    session = request.session
    if 'periodFinish' not in session:
        session['periodFinish'] = get_last_day(date.today()).strftime('%d-%b-%Y')
    return session['periodFinish']


@view_config(route_name='api_auth', renderer='json')
def user_permission(request):
    user_id = authenticated_userid(request)
    if user_id is None:
        auth = {'isAuthenticated': False, 'perms': {}}
    elif 'auth' in request.session:
        auth = request.session['auth']
    else:
        user = User.by_id(uuid.UUID(user_id))
        auth = {'isAuthenticated': True, 'Name': user.name, 'UserID': user.id}
        session_perms = groupfinder(user.id, request)
        perms = {}
        for item in Role.list():
            perms[item.name] = True if item.name in session_perms else False
        auth['perms'] = perms
        request.session['auth'] = auth
    return auth


def get_first_day(dt, d_years=0, d_months=0):
    # d_years, d_months are "deltas" to apply to dt
    y, m = dt.year + d_years, dt.month + d_months
    a, m = divmod(m - 1, 12)
    return date(y + a, m + 1, 1)


def get_last_day(dt):
    return get_first_day(dt, 0, 1) + timedelta(-1)
