import uuid

import pkg_resources
from pyramid.response import Response, FileResponse
from pyramid.view import view_config
from sqlalchemy import desc
import transaction

from brewman.models import DBSession
from brewman.models.auth import Client, LoginHistory
from brewman.models.validation_exception import TryCatchFunction


@view_config(request_method='GET', route_name='client_list', permission='Clients')
@view_config(request_method='GET', route_name='client_id', permission='Clients')
def html(request):
    package, resource = 'brewman:static/base.html'.split(':', 1)
    file = pkg_resources.resource_filename(package, resource)
    return FileResponse(file, request=request)


@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']))
    item.enabled = request.json_body['Enabled']
    if item.enabled:
        item.otp = None
    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 not found")
        response.status_int = 500
        return response

    client = Client.by_id(id)
    LoginHistory.__table__.delete(LoginHistory.client_id == client.id).execute()
    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:
        last_login = DBSession.query(LoginHistory) \
            .filter(LoginHistory.client_id == item.id).order_by(desc(LoginHistory.date)).first()
        last_login = 'Never' if last_login is None else last_login.date.strftime('%d-%b-%Y %H:%M')
        clients.append(
            {'ClientID': item.id, 'Code': item.code, 'Name': item.name, 'Enabled': item.enabled, 'OTP': item.otp,
             'CreationDate': item.creation_date.strftime('%d-%b-%Y %H:%M'), 'LastLogin': last_login,
             '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}


