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 Modifier, ProductGroup, ModifierProductGroup
from ..models.validation_exception import TryCatchFunction, ValidationError


@view_config(route_name='modifier_list', permission='Authenticated')
@view_config(request_method='GET', route_name='modifier_id', permission='Modifiers')
@view_config(request_method='GET', route_name='modifier', permission='Modifiers')
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_modifier', renderer='json', permission='Modifiers')
@TryCatchFunction
def save(request):
    name = request.json_body.get('Name', '').strip()
    if name == '':
        raise ValidationError('Validation', 'Name cannot be blank')
    is_active = request.json_body['IsActive']
    item = Modifier(name, is_active)
    add_groups(item, request.json_body['AllGroups'], request.json_body['Groups'])
    DBSession.add(item)
    transaction.commit()
    return modifier_info(item.id)


@view_config(request_method='POST', route_name='api_modifier_id', renderer='json', permission='Modifiers')
@TryCatchFunction
def update(request):
    item = Modifier.by_id(uuid.UUID(request.matchdict['id']))
    name = request.json_body.get('Name', '').strip()
    if name == '':
        raise ValidationError('Validation', 'Name cannot be blank')
    item.name = name
    item.is_active = request.json_body['IsActive']
    add_groups(item, request.json_body['AllGroups'], request.json_body['Groups'])
    transaction.commit()
    return modifier_info(item.id)


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

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


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


@view_config(request_method='GET', route_name='api_modifier', renderer='json', permission='Modifiers')
def show_blank(request):
    return modifier_info(None)


@view_config(request_method='GET', route_name='api_modifier', request_param='l', renderer='json',
             permission='Authenticated')
def show_list(request):
    list = DBSession.query(Modifier).order_by(Modifier.name).all()
    modifiers = []
    for item in list:
        modifier = {'Name': item.name, 'IsActive': item.is_active, 'AllGroups': False, 'Groups': [],
                    'Url': request.route_url('modifier_id', id=item.id)}
        for group in item.groups:
            if group.product_group_id is None:
                modifier['AllGroups'] = True
                modifier['Groups'] = []
                break
            else:
                modifier['Groups'].append(group.group.name)
        modifiers.append(modifier)
    return modifiers


@view_config(request_method='GET', route_name='api_modifier', request_param='s', renderer='json',
             permission='Authenticated')
def show_small(request):
    list = DBSession.query(Modifier).order_by(Modifier.name).all()
    modifiers = []
    for item in list:
        modifiers.append({'ModifierID': item.id, 'Name': item.name, 'IsActive': item.is_active})
    return modifiers


def modifier_info(id):
    groups = ProductGroup.list()
    if id is None:
        modifier = {'IsActive': True, 'AllGroups': False, 'Groups': []}
        for group in groups:
            modifier['Groups'].append({'ProductGroupID': group.id, 'Name': group.name, 'Enabled': False})
    else:
        item = Modifier.by_id(id)
        modifier = {'ModifierID': item.id, 'Name': item.name, 'IsActive': item.is_active, 'AllGroups': False,
                    'Groups': []}
        enabled = [g.group.id if g.group is not None else None for g in item.groups]
        for group in groups:
            modifier['Groups'].append({'ProductGroupID': group.id,
                                       'Name': group.name, 'Enabled': True if group.id in enabled else False})
        modifier['AllGroups'] = None in enabled
    return modifier


def add_groups(modifier, all_groups, groups):
    catch_all = [group for group in modifier.groups if group.group is None]
    catch_all = None if len(catch_all) == 0 else catch_all[0]
    others = [group for group in modifier.groups if group.group is not None]

    if all_groups:
        for other in others:
            DBSession.delete(other)
        if catch_all is None:
            modifier.groups.append(ModifierProductGroup(product_group_id=None))
    else:
        if catch_all is not None:
            DBSession.delete(catch_all)

        for group in groups:
            id = uuid.UUID(group['ProductGroupID'])
            pg = [g for g in modifier.groups if g.product_group_id == id]
            pg = None if len(pg) == 0 else pg[0]
            if group['Enabled'] and pg is None:
                modifier.groups.append(ModifierProductGroup(product_group_id=id))
            elif not group['Enabled'] and pg:
                DBSession.delete(pg)


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