import uuid
import pkg_resources
from pyramid.response import Response, FileResponse

from pyramid.view import view_config
import transaction
from brewman.models import DBSession

from brewman.models.master import CostCentre
from brewman.models.validation_exception import ValidationError, TryCatchFunction


@view_config(route_name='cost_centre_list', permission='Authenticated')
@view_config(request_method='GET', route_name='cost_centre_id', permission='Cost Centres')
@view_config(request_method='GET', route_name='cost_centre', permission='Cost Centres')
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_cost_centre', renderer='json', permission='Cost Centres')
@TryCatchFunction
def save(request):
    item = CostCentre(request.json_body['Name'])
    DBSession.add(item)
    transaction.commit()
    return cost_centre_info(item.id)


@view_config(request_method='POST', route_name='api_cost_centre_id', renderer='json', permission='Cost Centres')
@TryCatchFunction
def update(request):
    item = CostCentre.by_id(uuid.UUID(request.matchdict['id']))
    if item.is_fixture:
        raise ValidationError("{0} is a fixture and cannot be edited or deleted.".format(item.name))
    item.name = request.json_body['Name']
    transaction.commit()
    return cost_centre_info(item.id)


@view_config(request_method='DELETE', route_name='api_cost_centre_id', renderer='json', permission='Cost Centres')
def delete(request):
    item = request.matchdict.get('id', None)
    item = None if item is None else CostCentre.by_id(uuid.UUID(item))

    if item is None:
        response = Response("Cost Centre not found")
        response.status_int = 500
        return response
    elif item.is_fixture:
        raise ValidationError("{0} is a fixture and cannot be edited or deleted.".format(item.name))
    else:
        response = Response("Cost Centre deletion not implemented")
        response.status_int = 500
        return response


@view_config(request_method='GET', route_name='api_cost_centre_id', renderer='json', permission='Cost Centres')
def show_id(request):
    return cost_centre_info(uuid.UUID(request.matchdict.get('id', None)))


@view_config(request_method='GET', route_name='api_cost_centre', renderer='json', permission='Cost Centres')
def show_blank(request):
    return cost_centre_info(None)


@view_config(request_method='GET', route_name='api_cost_centre', request_param='list', renderer='json',
             permission='Authenticated')
def show_list(request):
    list = CostCentre.list()
    cost_centres = []
    for item in list:
        cost_centres.append({'CostCentreID': item.id, 'Name': item.name, 'IsFixture': item.is_fixture,
                             'Url': request.route_url('cost_centre_id', id=item.id)})
    return cost_centres


def cost_centre_info(id):
    if id is None:
        return {}
    else:
        cost_centre = CostCentre.by_id(id)
        return {'CostCentreID': cost_centre.id, 'Name': cost_centre.name, 'IsFixture': cost_centre.is_fixture}


