import uuid
from picard import groupfinder

__author__ = 'tanshu'

import pkg_resources
from pyramid.httpexceptions import HTTPFound
from pyramid.response import Response, FileResponse
from pyramid.security import remember, forget, authenticated_userid

from pyramid.view import view_config
from ..models.auth import User, Permission


@view_config(route_name='login')
def html(request):
    package, resource = 'picard:static/base.html'.split(':', 1)
    icon = pkg_resources.resource_filename(package, resource)
    return FileResponse(icon, request=request)


@view_config(route_name='logout')
def logout(request):
    request.session.invalidate()
    headers = forget(request)
    return HTTPFound(location=request.route_url('home'), headers=headers)


@view_config(request_method='POST', route_name='api_login', renderer='json')
def login(request):
    username = request.json_body.get('username', None)
    password = request.json_body.get('password', None)
    found, user = User.auth(username, password)

    if found:
        headers = remember(request, str(user.id))
        request.response.headers = headers
        return request.response
    else:
        response = Response("Login failed")
        response.status_int = 403
        return response


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