# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from os import path
import zipfile

from django.contrib import messages
from django.http.response import HttpResponse
from django.shortcuts import render
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

import openpyxl
from openpyxl.writer.excel import save_virtual_workbook

from . import forms, lib


def converter(request):
    json_form = forms.JsonForm(prefix="json")
    xlsx_form = forms.XlsxForm(prefix="xlsx")
    now = timezone.now()

    if request.method == 'POST':
        if request.POST.get('format') == 'to_xlsx':
            json_form = forms.JsonForm(data=request.POST, files=request.FILES, prefix="json")
            if json_form.is_valid():
                file = json_form.cleaned_data['file']
                try:
                    wb = lib.c2json_to_xlsx(file.read().decode('utf-8'))
                except ValueError:
                    messages.error(request, _("Invalid JSON file."))
                except AssertionError:
                    messages.error(request, _(u"This JSON file is not in the expected format."))
                else:
                    output = save_virtual_workbook(wb)

                    response = HttpResponse(
                        content=output,
                        content_type="application/json; charset=utf-8"
                    )
                    # Filename
                    basename, _extension = path.splitext(file.name)
                    filename = basename + now.strftime("_%Y%m%d-%H%M%S.xlsx")
                    # Force download
                    response['Content-Disposition'] = "attachment; filename=%s" % filename
                    return response

        elif request.POST.get('format') == "to_json":
            xlsx_form = forms.XlsxForm(data=request.POST, files=request.FILES or None, prefix="xlsx")
            if xlsx_form.is_valid():
                file = xlsx_form.cleaned_data['file']
                try:
                    wb = openpyxl.load_workbook(file)
                    output = lib.xlsx_to_c2json(wb)
                except zipfile.BadZipfile:
                    messages.error(request, _(u"Invalid or truncated XLSX file."))
                except AssertionError:
                    messages.error(request, _(u"This XLSX file is not in the expected format."))
                else:
                    response = HttpResponse(
                        content=output.encode('utf-8'),
                        content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    )
                    # Filename
                    basename, _extension = path.splitext(file.name)
                    filename = basename + now.strftime("_%Y%m%d-%H%M%S.json")
                    # Force download
                    response['Content-Disposition'] = "attachment; filename=%s" % filename
                    return response

    return render(
        request,
        "c2json.html",
        {
            'json_form': json_form,
            'xlsx_form': xlsx_form,
        }
    )
