import json

__author__ = 'tanshu'

from decimal import Decimal
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 Tax
from ..models.validation_exception import TryCatchFunction, ValidationError


@view_config(route_name='tax_list', permission='Authenticated')
@view_config(request_method='GET', route_name='tax_id', permission='Taxes')
@view_config(request_method='GET', route_name='tax', permission='Taxes')
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_tax', renderer='json', permission='Taxes')
@TryCatchFunction
def save(request):
    name = request.json_body.get('Name', '').strip()
    if name == '':
        raise ValidationError('Validation', 'Name cannot be blank')
    rate = round(Decimal(request.json_body.get('Rate', 0)) / 100, 5)
    item = Tax(name, rate)
    DBSession.add(item)
    transaction.commit()
    return tax_info(item.id)


@view_config(request_method='POST', route_name='api_tax_id', renderer='json', permission='Taxes')
@TryCatchFunction
def update(request):
    item = Tax.by_id(uuid.UUID(request.matchdict['id']))
    if item.is_fixture:
        raise ValidationError('Fixture', "{0} cannot be edited or deleted.".format(item.name))
    name = request.json_body.get('Name', '').strip()
    if name == '':
        raise ValidationError('Validation', 'Name cannot be blank')
    rate = round(Decimal(request.json_body.get('Rate', 0)) / 100, 5)
    item.name = name
    item.rate = rate
    transaction.commit()
    return tax_info(item.id)


@view_config(request_method='DELETE', route_name='api_tax_id', renderer='json', permission='Taxes')
@TryCatchFunction
def delete(request):
    tax = Tax.by_id(uuid.UUID(request.matchdict['id']))
    can_delete, reason = tax.can_delete('Advanced Delete' in groupfinder(authenticated_userid(request), request))

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


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


@view_config(request_method='GET', route_name='api_tax', renderer='json', permission='Taxes')
def show_blank(request):
    return tax_info(None)


@view_config(request_method='GET', route_name='api_tax', request_param='l', renderer='json',
             permission='Authenticated')
def show_list(request):
    list = DBSession.query(Tax).order_by(Tax.name).all()
    taxes = []
    for item in list:
        taxes.append({'Name': item.name, 'Rate': item.rate * 100, 'IsFixture': item.is_fixture,
                      'Url': request.route_url('tax_id', id=item.id)})
    return taxes


@view_config(request_method='GET', route_name='api_tax', request_param='s', renderer='json',
             permission='Authenticated')
def show_small(request):
    list = DBSession.query(Tax).order_by(Tax.name).all()
    taxes = []
    for item in list:
        taxes.append({'TaxID': item.id, 'Name': item.name, 'Rate': item.rate * 100})
    return taxes


def tax_info(id):
    if id is None:
        tax = {}
    else:
        tax = Tax.by_id(id)
        tax = {'TaxID': tax.id, 'Name': tax.name, 'Rate': tax.rate * 100, 'IsFixture': tax.is_fixture}
    return tax


def delete_with_data(tax):
    #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 == tax.id)) \
    #    .all()
    #
    #for voucher in query:
    #    others, sus_inv, prod_inv = False, None, None
    #    for inventory in voucher.inventories:
    #        if inventory.product_id == tax.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.tax = 0
    #            prod_inv.discount = 0
    #            prod_inv.batch = suspense_batch
    #            voucher.narration += '\nSuspense \u20B9{0:,.2f} is {1}'.format(prod_inv.amount, tax.name)
    #        else:
    #            sus_inv.quantity += prod_inv.amount
    #            DBSession.delete(prod_inv)
    #            voucher.narration += '\nDeleted \u20B9{0:,.2f} of {1}'.format(prod_inv.amount, tax.name)
    #for batch in tax.batches:
    #    DBSession.delete(batch)
    DBSession.delete(tax)
