import uuid

from pyramid.response import Response
from pyramid.view import view_config
import transaction
from brewman.models import DBSession
from brewman.models.auth import Group, Role
from brewman.models.validation_exception import ValidationError, TryCatchFunction

@view_config(route_name='group_list', renderer='brewman:templates/angular_base.mako', permission='Users')
@view_config(request_method='GET', route_name='group_id', renderer='brewman:templates/angular_base.mako',
    permission='Users')
@view_config(request_method='GET', route_name='group', renderer='brewman:templates/angular_base.mako',
    permission='Users')
def html(request):
    return {}


@view_config(request_method='POST', route_name='api_group', renderer='json', permission='Users')
@TryCatchFunction
def save(request):
    group = Group(request.json_body['Name'])
    DBSession.add(group)
    add_permissions(group, request.json_body['Permissions'])
    transaction.commit()
    return group_info(group.id)


@view_config(request_method='POST', route_name='api_group_id', renderer='json', permission='Users')
@TryCatchFunction
def update(request):
    id = request.matchdict.get('id', None)
    group = Group.by_id(uuid.UUID(id))
    group.name = request.json_body['Name']
    add_permissions(group, request.json_body['Permissions'])
    transaction.commit()
    return group_info(group.id)


def add_permissions(group, permissions):
    for permission in permissions:
        id = uuid.UUID(permission['PermissionID'])
        gp = [p for p in group.roles if p.id == id]
        gp = None if len(gp) == 0 else gp[0]
        if permission['Enabled'] and gp is None:
            group.roles.append(Role.by_id(id))
        elif not permission['Enabled'] and gp:
            group.roles.remove(gp)


@view_config(request_method='DELETE', route_name='api_group_id', renderer='json', permission='Users')
def delete(request):
    id = request.matchdict.get('id', None)
    if id is None:
        response = Response("Group is Null")
        response.status_int = 500
        return response
    else:
        response = Response("Group deletion not implemented")
        response.status_int = 500
        return response


@view_config(request_method='GET', route_name='api_group_id', renderer='json', permission='Users')
def show_id(request):
    return group_info(uuid.UUID(request.matchdict.get('id', None)))


@view_config(request_method='GET', route_name='api_group', renderer='json', permission='Users')
def show_blank(request):
    return group_info(None)


@view_config(request_method='GET', route_name='api_group', renderer='json', request_param='list', permission='Users')
def show_list(request):
    list = Group.list()
    groups = []
    for item in list:
        group = {'Name': item.name, 'Permissions': [], 'Url': request.route_url('group_id', id=item.id)}
        for permission in item.roles:
            group['Permissions'].append(permission.name)
        groups.append(group)
    return groups


def group_info(id):
    if id is None:
        group = {'Name': '', 'Permissions': []}
        for item in Role.list():
            group['Permissions'].append({'PermissionID': item.id, 'Name': item.name, 'Enabled': False})
    else:
        group_object = Group.by_id(id)
        group = {'GroupID': group_object.id, 'Name': group_object.name, 'Permissions': []}
        for item in Role.list():
            group['Permissions'].append(
                {'PermissionID': item.id, 'Name': item.name, 'Enabled': True if item in group_object.roles else False})
    return group


