from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse

from datetime import datetime

from django.template.defaultfilters import slugify
from finance_utilities.common.user_util import is_user_in_group, get_username

import xlwt
from xlwt import easyxf

from finance_utilities.hcom_training.models import *
from finance_utilities.hcom_training.trainee_xls_maker import make_trainee_roster



def view_hcom_trainee_xls(request):
    if not (request.user.is_authenticated() and request.user.is_staff):  
        return HttpResponse('not accessible')
    
    lu = get_username(request)
   
    if request.method == 'GET':  
        kwargs = {}
        for x,y in request.GET.iteritems():
            if not str(x) in ['ot', 'o', 'q']:
                kwargs.update({str(x):str(y)})
        #print kwargs
        try:
            trainees = Trainee.objects.filter(**kwargs).order_by('training_order','lname','fname')
        except:
            trainees = Trainee.objects.all().order_by('training_order','lname','fname')    
    else:
        trainees = Trainee.objects.all().order_by('training_order','lname','fname')
    
    if trainees.count() == 0:
        return HttpResponse('Sorry!  No trainees are in this list.<br />Please press the back button on your browser.')
    
    book = xlwt.Workbook(encoding="utf-8")
    # With a workbook object made we can now add some sheets.
    sheet1 = book.add_sheet('hcom training')

    date_obj = datetime.now()
    info_line = "Generated by: %s on %s" % (lu['username'] , date_obj.strftime('%m/%d/%Y - %I:%M %p'))

    sheet1 = make_trainee_roster(sheet1, info_line, trainees)

    # create response object
    response = HttpResponse(mimetype='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=hcom_trainees_%s.xls' % (date_obj.strftime('%m%d-%I').lower()) 

    # send .xls spreadsheet to response stream
    book.save(response)
    return response
    


