# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2016 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 os

from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.views.generic import CreateView, DeleteView, UpdateView, View

from .forms import QueryForm
from .models import CsvDataSource, Query


class NewQueryView(CreateView):
    model = Query
    form_class = QueryForm
    template_name = 'csvdatasource/query_form.html'

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['resource'] = CsvDataSource.objects.get(slug=self.kwargs['connector_slug'])
        return ctx

    def get_initial(self):
        return {'resource': CsvDataSource.objects.get(slug=self.kwargs['connector_slug']).id}

    def get_success_url(self):
        return self.object.resource.get_absolute_url()


class UpdateQueryView(UpdateView):
    model = Query
    form_class = QueryForm
    template_name = 'csvdatasource/query_form.html'

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['resource'] = CsvDataSource.objects.get(slug=self.kwargs['connector_slug'])
        return ctx

    def get_success_url(self):
        return self.object.resource.get_absolute_url()


class DeleteQueryView(DeleteView):
    model = Query

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['resource'] = CsvDataSource.objects.get(slug=self.kwargs['connector_slug'])
        return ctx

    def get_success_url(self):
        return self.object.resource.get_absolute_url()


class CsvDownload(View):
    def get(self, request, *args, **kwargs):
        obj = get_object_or_404(CsvDataSource, slug=kwargs.get('connector_slug'))
        file_extension = os.path.splitext(obj.csv_file.name)[-1]
        mime_type = {
            '.xls': 'application/vnd.ms-excel',
            '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            '.ods': 'application/vnd.oasis.opendocument.spreadsheet',
            '.csv': 'text/csv; charset=utf-8',
        }.get(file_extension) or 'application/octet-stream'
        response = HttpResponse(obj.csv_file, content_type=mime_type)
        response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(obj.csv_file.name)
        return response
