from django.http import HttpResponseRedirect
from django.shortcuts import render
from formare.models.formatter_results import FormatterResults
from django.http import HttpResponse
from django.core.urlresolvers import reverse
import csv
import os
from datetime import datetime

def home(request):
    context = {}
    return render(request, 'formare/home.html', context)

def error(request):
    context = {}
    return render(request, 'formare/error.html', context)

def upload_file(request):
    if request.method == 'POST':
        formatter = FormatterResults()
        formatter.result = None
        formatter.error = None
        formatter.run_date = datetime.now()

        try:
            if 'file' in request.FILES:
                uploadedfile = request.FILES['file']
            else:
                raise Exception('No file specified')

            lines = formatter.run(uploadedfile)
        except Exception as e:
            formatter.error = str(e)
            formatter.result = 'Encountered fatal error'
            formatter.save()
            return HttpResponseRedirect(reverse('error'))

        response = HttpResponse(content_type='text/csv')
        filename = '%s-b' % os.path.splitext(uploadedfile.name)[0]
        response['Content-Disposition'] = 'attachment; filename="%s.csv"' % filename
        writer = csv.writer(response)

        for line in lines:
            writer.writerow(line)

        formatter.save()

        return response
