import datetime
import uuid
from pyramid.security import authenticated_userid
from pyramid.view import view_defaults, view_config
import transaction
from brewman.models.auth import User
from brewman.models.validation_exception import TryCatchFunction, ValidationError
from brewman.models.voucher import Voucher
from brewman.views import get_lock_info
from brewman.views.services.session import session_current_date_set
from . import voucher_info, journal_create_voucher, purchase_create_voucher, issue_create_voucher
from .purchase_return import purchase_return_create_voucher
from .salary_deduction import salary_deduction_create_voucher

__author__ = 'tanshu'


@view_defaults(request_method='POST', route_name='api_voucher', renderer='json')
class save_voucher(object):
    def __init__(self, request):
        self.request = request
        self.user = User.by_id(uuid.UUID(authenticated_userid(request)))
        self.json = request.json_body
        self.start, self.finish = get_lock_info()
        self.voucher_date = datetime.datetime.strptime(self.json['Date'], '%d-%b-%Y')


    @view_config(request_param='type=Journal', permission='Journal')
    def journal(self):
        return self.save()


    @view_config(request_param='type=Payment', permission='Payment')
    def payment(self):
        return self.save()


    @view_config(request_param='type=Receipt', permission='Receipt')
    def receipt(self):
        return self.save()


    @view_config(request_param='type=Purchase', permission='Purchase')
    def purchase(self):
        return self.save()


    @view_config(request_param='type=Purchase Return', permission='Purchase Return')
    def purchase_return(self):
        return self.save()


    @view_config(request_param='type=Issue', permission='Issue')
    def issue(self):
        return self.save()

    @view_config(request_param='type=Salary Deduction', permission='Salary Deduction')
    def salary_deduction(self):
        return self.save()

    @TryCatchFunction
    def save(self):
        if self.start is not None and self.start > self.voucher_date:
            raise ValidationError("Vouchers before {0} have been locked.".format(self.start.strftime('%d-%b-%Y')))
        elif self.finish is not None and self.finish < self.voucher_date:
            raise ValidationError("Vouchers after {0} have been locked.".format(self.finish.strftime('%d-%b-%Y')))

        if self.json['Type'] in ['Journal', 'Payment', 'Receipt']:
            voucher = journal_create_voucher(self.json, self.user)
        elif self.json['Type'] in ['Purchase']:
            voucher = purchase_create_voucher(self.json, self.user)
        elif self.json['Type'] in ['Purchase Return']:
            voucher = purchase_return_create_voucher(self.json, self.user)
        elif self.json['Type'] in ['Issue']:
            voucher = issue_create_voucher(self.json, self.user)
        elif self.json['Type'] in ['Salary Deduction']:
            voucher = salary_deduction_create_voucher(self.json, self.user)
        transaction.commit()
        session_current_date_set(self.request, self.json['Date'])
        return voucher_info(Voucher.by_id(voucher.id))
