import datetime
from pyramid.view import view_config
from sqlalchemy import or_
from ..models import DBSession
from ..models.master import AttendanceType, Employee
from ..models.voucher import Attendance
from .attendance import daterange
from .services.session import  session_period_start, session_period_finish

__author__ = 'tanshu'

@view_config(route_name='attendance_report', renderer='csv', permission='Attendance')
def get_report(request):
    start_date = request.GET.get('StartDate', session_period_start(request))
    finish_date = request.GET.get('FinishDate', session_period_finish(request))
    start_date = datetime.datetime.strptime(start_date, '%d-%b-%Y')
    finish_date = datetime.datetime.strptime(finish_date, '%d-%b-%Y')
    header, report = attendance_record(start_date, finish_date)
    return {'header': header, 'rows': report, 'filename': 'Attendance Record.csv'}


def attendance_record(start_date, finish_date):
    report = []
    header = ["Code", "Name", "Designation", "Department", "Salary", "SC Points"]
    for date in daterange(start_date, finish_date, inclusive=True):
        header.append(date.strftime('%d-%b'))

    not_set = AttendanceType.by_id(0)
    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:
        row_display = [employee.code, employee.name, employee.designation, employee.costcenter.name, employee.salary,
                       employee.service_points]
        row_value = ['', '', '', '', employee.salary, employee.service_points]
        for date in daterange(start_date, finish_date, inclusive=True):
            att = DBSession.query(Attendance)\
            .filter(Attendance.employee_id == employee.id)\
            .filter(Attendance.date == date)\
            .filter(Attendance.is_valid == True)\
            .first()
            att = not_set if att is None else AttendanceType.by_id(att.attendance_type)
            row_display.append(att.name)
            row_value.append(att.value)
        report.extend([tuple(row_display), tuple(row_value)])
    return header, report