import json

__author__ = 'tanshu'

import uuid

import pkg_resources
from pyramid.response import Response, FileResponse
from pyramid.security import authenticated_userid
from pyramid.view import view_config
import transaction

from .. import groupfinder
from ..models import DBSession
from ..models.master import FoodTable
from ..models.validation_exception import TryCatchFunction, ValidationError


@view_config(route_name='food_table_list', permission='Authenticated')
@view_config(request_method='GET', route_name='food_table_id', permission='Food Tables')
@view_config(request_method='GET', route_name='food_table', permission='Food Tables')
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(request_method='POST', route_name='api_food_table', renderer='json', permission='Food Tables')
@TryCatchFunction
def save(request):
    name = request.json_body.get('Name', '').strip()
    if name == '':
        raise ValidationError('Validation', 'Name cannot be blank')
    location = request.json_body.get('Location', '').strip()
    item = FoodTable(name, location)
    DBSession.add(item)
    transaction.commit()
    return food_table_info(item.id)


@view_config(request_method='POST', route_name='api_food_table_id', renderer='json', permission='Food Tables')
@TryCatchFunction
def update(request):
    item = FoodTable.by_id(uuid.UUID(request.matchdict['id']))
    name = request.json_body.get('Name', '').strip()
    if name == '':
        raise ValidationError('Validation', 'Name cannot be blank')
    location = request.json_body.get('Location', '').strip()
    item.name = name
    item.rate = location
    transaction.commit()
    return food_table_info(item.id)


@view_config(request_method='DELETE', route_name='api_food_table_id', renderer='json', permission='Food Tables')
@TryCatchFunction
def delete(request):
    food_table = FoodTable.by_id(uuid.UUID(request.matchdict['id']))
    can_delete, reason = food_table.can_delete('Advanced Delete' in groupfinder(authenticated_userid(request), request))

    if can_delete:
        delete_with_data(food_table)
        transaction.commit()
        return food_table_info(None)
    else:
        transaction.abort()
        response = Response(json.dumps(reason))
        response.status_int = 500
        return response


@view_config(request_method='GET', route_name='api_food_table_id', renderer='json', permission='Food Tables')
def show_id(request):
    return food_table_info(uuid.UUID(request.matchdict.get('id', None)))


@view_config(request_method='GET', route_name='api_food_table', renderer='json', permission='Food Tables')
def show_blank(request):
    return food_table_info(None)


@view_config(request_method='GET', route_name='api_food_table', request_param='l', renderer='json',
             permission='Authenticated')
def show_list(request):
    list = DBSession.query(FoodTable).order_by(FoodTable.name).all()
    food_tables = []
    for item in list:
        food_tables.append({'Name': item.name, 'Location': item.location,
                            'Url': request.route_url('food_table_id', id=item.id)})
    return food_tables


@view_config(request_method='GET', route_name='api_food_table', request_param='s', renderer='json',
             permission='Authenticated')
def show_small(request):
    list = DBSession.query(FoodTable).order_by(FoodTable.name).all()
    food_tables = []
    for item in list:
        food_tables.append({'FoodTableID': item.id, 'Name': item.name, 'Location': item.location})
    return food_tables


def food_table_info(id):
    if id is None:
        food_table = {}
    else:
        food_table = FoodTable.by_id(id)
        food_table = {'FoodTableID': food_table.id, 'Name': food_table.name, 'Location': food_table.location}
    return food_table


def delete_with_data(food_table):
    #suspense_product = Product.by_id(Product.suspense())
    #suspense_batch = Batch.by_id(Batch.suspense())
    #query = Voucher.query().options(joinedload_all(Voucher.inventories, Inventory.product, innerjoin=True)) \
    #    .filter(Voucher.inventories.any(Inventory.product_id == food_table.id)) \
    #    .all()
    #
    #for voucher in query:
    #    others, sus_inv, prod_inv = False, None, None
    #    for inventory in voucher.inventories:
    #        if inventory.product_id == food_table.id:
    #            prod_inv = inventory
    #        elif inventory.product_id == Product.suspense():
    #            sus_inv = inventory
    #        else:
    #            others = True
    #    if not others and voucher.type == VoucherType.by_id('Issue'):
    #        DBSession.delete(voucher)
    #    else:
    #        if sus_inv is None:
    #            prod_inv.product = suspense_product
    #            prod_inv.quantity = prod_inv.amount
    #            prod_inv.rate = 1
    #            prod_inv.food_table = 0
    #            prod_inv.discount = 0
    #            prod_inv.batch = suspense_batch
    #            voucher.narration += '\nSuspense \u20B9{0:,.2f} is {1}'.format(prod_inv.amount, food_table.name)
    #        else:
    #            sus_inv.quantity += prod_inv.amount
    #            DBSession.delete(prod_inv)
    #            voucher.narration += '\nDeleted \u20B9{0:,.2f} of {1}'.format(prod_inv.amount, food_table.name)
    #for batch in food_table.batches:
    #    DBSession.delete(batch)
    DBSession.delete(food_table)
