import datetime
import os
import shutil
import tempfile

from flask import render_template, redirect, url_for
from flask.ext.security import login_required, current_user

from . import report
from .forms import BasicReportForm, ProblemIdsReportForm
from ..args import BasicReport, ProblemIdsReport, SendEmail
from edx_data_research import reporting, tasks


@report.route('/')
@login_required
def index():
    return render_template('report/index.html')


@report.route('/problemids', methods=['GET', 'POST'])
@login_required
def report_problem_ids():
    form = ProblemIdsReportForm()
    if form.validate_on_submit():
        try:
            temp_dir = tempfile.mkdtemp()
            course = form.course.data
            anonymize = form.anonymize.data
            problem_ids = form.problem_ids.data
            problem_ids = [problem_id.strip() for problem_id in problem_ids.split(',')]
            final_attempt = form.final_attempt.data
            include_email = form.include_email.data
            #end_date = datetime.datetime.today().date() - datetime.timedelta(days=1)
            end_date = datetime.datetime(2016, 03, 06).date() - datetime.timedelta(days=1)
            start_date = end_date - datetime.timedelta(days=6)
            args = ProblemIdsReport(course, 'localhost', problem_ids, final_attempt,
                                    include_email, start_date, end_date, temp_dir, 10000,
                                    anonymize, None)
            edx_obj = reporting.ProblemIds(args)
            edx_obj.problem_ids()
            
            attachments = [os.path.join(temp_dir, _file)
                           for _file in os.listdir(temp_dir)]
            from_address = os.environ['FROM_EMAIL_ADDRESS']
            password = os.environ['FROM_EMAIL_PASSWORD']
            to_address = [current_user.email]
            subject = 'Weekly Report for {0} - {1}'.format(course.capitalize(),
                                                           datetime.datetime.today()
                                                           .date())
            args = SendEmail(from_address, None, password, to_address, None,
                             subject, attachments)
            email = tasks.Email(args)
            email.do()
        finally:
            shutil.rmtree(temp_dir)
        return redirect(url_for('report.report_problem_ids'))
    return render_template('report/problem_ids.html', form=form)


@report.route('/basic', methods=['GET', 'POST'])
@login_required
def report_basic():
    form = BasicReportForm()
    if form.validate_on_submit():
        try:
            temp_dir = tempfile.mkdtemp()
            course = form.course.data
            report_name = form.report.data
            anonymize = form.anonymize.data
            args = BasicReport(course, 'localhost', report_name, anonymize,
                               temp_dir, 10000)
            edx_obj = reporting.Basic(args)
            getattr(edx_obj, report_name)()

            attachments = [os.path.join(temp_dir, _file)
                           for _file in os.listdir(temp_dir)]
            from_address = os.environ['FROM_EMAIL_ADDRESS']
            password = os.environ['FROM_EMAIL_PASSWORD']
            to_address = [current_user.email]
            subject = 'Weekly Report for {0} - {1}'.format(course.capitalize(),
                                                           datetime.datetime.today()
                                                           .date())
            args = SendEmail(from_address, None, password, to_address, None,
                             subject, attachments)
            email = tasks.Email(args)
            email.do()
        finally:
            shutil.rmtree(temp_dir)
        return redirect(url_for('report.report_basic'))
    return render_template('report/basic.html', form=form)

@@ -302,16 +302,65 @@
 ndEmail%0A
+from ..utils import send_email, temp_dir_context%0A
 from edx
@@ -398,16 +398,16 @@
 , tasks%0A
-
 %0A%0A@repor
@@ -674,54 +674,44 @@
     
-try:%0A            temp_dir = tempfile.mkdtemp()
+with temp_dir_context() as temp_dir:
 %0A   
@@ -1716,171 +1716,8 @@
 r)%5D%0A
-            from_address = os.environ%5B'FROM_EMAIL_ADDRESS'%5D%0A            password = os.environ%5B'FROM_EMAIL_PASSWORD'%5D%0A            to_address = %5Bcurrent_user.email%5D%0A
     
@@ -1727,38 +1727,42 @@
      subject = '
-Weekly
+ProblemIds
  Report for %7B0%7D 
@@ -1788,32 +1788,36 @@
 e.capitalize(),%0A
+    
                 
@@ -1936,32 +1936,36 @@
                 
+    
 .date())%0A       
@@ -1973,236 +1973,59 @@
     
-args = SendE
+send_e
 mail(
-from_address, None, password, to_address, None,%0A                             subject, attachments)%0A            email = tasks.Email(args)%0A            email.do()%0A        finally:%0A            shutil.rmtree(temp_dir
+current_user.email, subject, attachments
 )%0A  
@@ -2311,54 +2311,44 @@
     
-try:%0A            temp_dir = tempfile.mkdtemp()
+with temp_dir_context() as temp_dir:
 %0A   
@@ -2817,218 +2817,134 @@
     
-from_address = os.environ%5B'FROM_EMAIL_ADDRESS'%5D%0A            password = os.environ%5B'FROM_EMAIL_PASSWORD'%5D%0A            to_address = %5Bcurrent_user.email%5D%0A            subject = 'Weekly Report for %7B0%7D - %7B1%7D'.format(
+subject = '%7B0%7D Report for %7B1%7D - %7B2%7D'.format(report_name.capitalize(),%0A                                                        
 cour
@@ -2952,35 +2952,32 @@
 e.capitalize(),%0A
-   
                 
@@ -3090,35 +3090,32 @@
                 
-   
 .date())%0A       
@@ -3123,236 +3123,59 @@
     
-args = SendE
+send_e
 mail(
-from_address, None, password, to_address, None,%0A                             subject, attachments)%0A            email = tasks.Email(args)%0A            email.do()%0A        finally:%0A            shutil.rmtree(temp_dir
+current_user.email, subject, attachments
 )%0A  

Refactor code