# barbacompta - invoicing for dummies
# Copyright (C) 2019-2020 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import csv
import os

from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.template import Context, Template
from django.utils.six import text_type
from django.utils.translation import ugettext_lazy as _


def export_as_csv(modeladmin, request, queryset):
    """
    Generic csv export admin action.
    """
    if not request.user.is_staff:
        raise PermissionDenied
    opts = modeladmin.model._meta
    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = "attachment; filename=%s.csv" % text_type(opts).replace(".", "_")
    writer = csv.writer(response)
    field_names = [field.name for field in opts.fields]
    m2m_field_names = [m2m_field.name for m2m_field in opts.many_to_many]
    # Write a first row with header information
    writer.writerow(field_names + m2m_field_names)
    # Write data rows
    for obj in queryset:
        values = [text_type(getattr(obj, field)) for field in field_names]
        for m2m_field in m2m_field_names:
            value = getattr(obj, m2m_field)
            value = ",".join(map(text_type, value.all()))
            values.append(text_type(value))
        writer.writerow(map(lambda x: text_type.encode(x, "utf8"), values))
    return response


export_as_csv.short_description = "Export selected objects as csv file"


def export_references_as_fodt(modeladmin, request, queryset):
    queryset = (
        queryset.exclude(public_description='')
        .exclude(client__picture__isnull=True)
        .exclude(client__picture='')
    )
    template = os.path.dirname(os.path.abspath(__file__)) + '/templates/admin/eo_facture/references.fodt'
    context = {'contracts': queryset, 'base_uri': request.build_absolute_uri('/').rstrip('/')}
    output_filename = 'references.fodt'
    mimetype = 'application/vnd.oasis.opendocument.text'

    with open(template) as fd:
        t = Template(fd.read())
    export = t.render(Context(context)).encode('utf-8')

    response = HttpResponse(content=export, content_type=mimetype)
    response['Content-Disposition'] = 'attachment; filename=%s' % output_filename
    return response


export_references_as_fodt.short_description = _("Export selected contracts as fodt file")
