from django.contrib.auth.models import User, Group
from django.shortcuts import redirect
from .models import Student, RebateReq, Meal, OverheadReq

def is_manager(user):
	return user.groups.filter(name='manager').exists()

def is_worker(user):
	return user.groups.filter(name='worker').exists()

def is_student(user):
	return user.groups.filter(name='student').exists()

def generate_pending_rebates():
	context = {'pending_rebates':[]}
	for reb in RebateReq.objects.filter(status='W'):
		context["pending_rebates"].extend([{
			'from': str(reb.fromDate),
			'to': str(reb.toDate),
			'ldap':reb.student.user.username,
			'name':f'{reb.student.user.first_name+reb.student.user.last_name}',
			'duration': str((reb.toDate-reb.fromDate).days)
			}])
	if len(context["pending_rebates"])==0:
		return None
	else:
		return context

def generate_pending_overheads():
	context = {'pending_overheads':[]}
	for ovr in OverheadReq.objects.filter(status='W'):
		context["pending_overheads"].extend([{
			'date': str(ovr.date),
			'ldap': ovr.student.user.username,
			'name':f'{ovr.student.user.first_name+ovr.student.user.last_name}',
			'mealType': ovr.mealType,
			'count': ovr.count
			}])
	if len(context["pending_overheads"])==0:
		return None
	else:
		return context

def generate_my_requests(user):
	context = {'prev_overheads':[], 'prev_rebates':[]}
	status = {'W':'HOLD', 'Y':'APPROVED', 'N':'REJECTED'}
	student = Student.objects.filter(user=user)[0]
	for ovr in OverheadReq.objects.filter(student=student):
		context["prev_overheads"].extend([{
			'date': str(ovr.date),
			'meal': ovr.mealType,
			'status': status[ovr.status],
			'count': ovr.count
			}])
	for reb in RebateReq.objects.filter(student=student):
		context["prev_rebates"].extend([{
			'from': str(reb.fromDate),
			'to': str(reb.toDate),
			'status': status[reb.status]
			}])
	if len(context["prev_overheads"])==0:
		context.pop("prev_overheads")
	elif len(context["prev_rebates"])==0:
		context.pop("prev_rebates")
	return context 

def homepage_redirect(request):
	user=request.user
	if is_manager(user):
		return redirect('manager-homepage')
	elif is_worker(user):
		return redirect('worker-homepage')
	else: #is_student(user):
		return redirect('student-homepage')