import calendar
import datetime
import uuid
from pyramid.security import authenticated_userid
from pyramid.view import view_config
from sqlalchemy import or_
import transaction
from ....models import DBSession
from ....models.auth import User
from ....models.master import Employee, AttendanceType, Ledger
from ....models.validation_exception import TryCatchFunction
from ....models.voucher import Voucher, VoucherType, Attendance, Journal
from ..session import get_first_day, get_last_day

__author__ = 'tanshu'


@view_config(request_method='POST', route_name='api_credit_salary', renderer='json', permission='Attendance')
@TryCatchFunction
def credit_salary(request):
    user = User.by_id(uuid.UUID(authenticated_userid(request)))
    month = datetime.datetime.strptime(request.json_body['Month'], '%d-%b-%Y')

    start_date = get_first_day(month)
    finish_date = get_last_day(month)
    voucher = Voucher(date=finish_date, narration='Auto Generated Salary Entry', user_id=user.id,
        type=VoucherType.by_name('Journal'), posted=True, poster_id=user.id)
    DBSession.add(voucher)
    for item in salary_journals(start_date, finish_date):
        voucher.journals.append(item)
        DBSession.add(item)
    transaction.commit()
    return {'message': 'Salary Entry created'}


def salary_journals(start_date, finish_date):
    days = calendar.monthrange(start_date.year, start_date.month)[1]
    finish_date = finish_date + datetime.timedelta(1)
    amount = 0
    journals = []
    employees = DBSession().query(Employee)\
    .filter(Employee.joining_date <= finish_date)\
    .filter(or_(Employee.is_active, Employee.leaving_date >= start_date))\
    .order_by(Employee.costcenter_id).order_by(Employee.designation).order_by(Employee.name).all()
    for employee in employees:
        att = DBSession.query(Attendance)\
        .filter(Attendance.employee_id == employee.id)\
        .filter(Attendance.date >= start_date)\
        .filter(Attendance.date < finish_date)\
        .filter(Attendance.is_valid == True)\
        .all()
        att = sum(map(lambda x: AttendanceType.by_id(x.attendance_type).value, att))
        att = round(att * employee.salary / days)
        amount += att
        journals.append(Journal(amount=att, debit=-1, ledger_id=employee.id, cost_center_id=employee.costcenter_id))
    salary = Ledger.salary()
    salary = Ledger.by_id(uuid.UUID(salary['LedgerID']))
    journals.append(Journal(amount=amount, debit=1, ledger_id=salary.id, cost_center_id=salary.costcenter_id))
    return journals

