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 Client

from brewman.models.validation_exception import TryCatchFunction


@view_config(request_method='GET', route_name='client_list', renderer='brewman:templates/angular_base.mako',
             permission='Clients')
@view_config(request_method='GET', route_name='client_id', renderer='brewman:templates/angular_base.mako',
    permission='Clients')
def html(request):
    return {}


@view_config(request_method='POST', route_name='api_client_id', renderer='json', permission='Clients')
@TryCatchFunction
def update(request):
    item = Client.by_id(uuid.UUID(request.matchdict['id']))
    if item.otp is None:
        item.enabled = request.json_body['Enabled']
    item.name = request.json_body['Name']
    transaction.commit()
    return {}


@view_config(request_method='DELETE', route_name='api_client_id', renderer='json', permission='Clients')
@TryCatchFunction
def delete(request):
    id = request.matchdict.get('id', None)
    if id is None:
        response = Response("Client is Null")
        response.status_int = 500
        return response

    client = Client.by_id(id)
    if client.enabled:
        response = Response("Client is enabled and cannot be deleted")
        response.status_int = 500
        return response
    else:
        DBSession.delete(client)
        transaction.commit()
        return {}


@view_config(request_method='GET', route_name='api_client', request_param='list', renderer='json', permission='Clients')
def show_list(request):
    list = Client.list()
    clients = []
    for item in list:
        clients.append(
            {'ClientID': item.id, 'Code': item.code, 'Name': item.name, 'Enabled': item.enabled, 'OTP': item.otp,
             'Url': request.route_url('client_id', id=item.id)})
    return clients


@view_config(request_method='GET', route_name='api_client_id', renderer='json', permission='Clients')
def show_id(request):
    item = Client.by_id(request.matchdict['id'])
    return {'ClientID': item.id, 'Code': item.code, 'Name': item.name, 'Enabled': item.enabled, 'OTP': item.otp}


