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

from django.http import HttpResponseRedirect, JsonResponse
from django.template import Context, Template, TemplateSyntaxError
from django.views.generic import CreateView, DeleteView, DetailView, UpdateView

from passerelle.base.mixins import ResourceChildViewMixin
from passerelle.utils.conversion import simplify

from . import models
from .forms import ComputedPropertyFormSet, QueryForm


class QueryMixin:
    def form_valid(self, form):
        self.object = form.save(commit=False)  # save object and update cache only once
        return HttpResponseRedirect(self.get_success_url())

    def post(self, *args, **kwargs):
        self.object = self.get_object()
        form = self.get_form()
        formset = ComputedPropertyFormSet(data=self.request.POST)
        if form.is_valid() and formset.is_valid():
            response = self.form_valid(form)
            self.object.computed_properties = {}
            for sub_data in formset.cleaned_data:
                if not sub_data.get('key'):
                    continue
                self.object.computed_properties[sub_data['key']] = sub_data['value']
            self.object.save()
            return response
        else:
            return self.form_invalid(form)


class QueryNew(QueryMixin, ResourceChildViewMixin, CreateView):
    model = models.Query
    form_class = QueryForm

    def get_object(self):
        return None

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        data = None
        if self.request.method == 'POST':
            data = self.request.POST
        context['formset'] = ComputedPropertyFormSet(data=data)
        return context

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['instance'] = self.model(resource=self.resource)
        return kwargs

    def get_changed_url(self):
        return self.object.get_absolute_url()


class QueryEdit(QueryMixin, ResourceChildViewMixin, UpdateView):
    model = models.Query
    form_class = QueryForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        data = None
        if self.request.method == 'POST':
            data = self.request.POST
        context['formset'] = ComputedPropertyFormSet(
            data=data,
            initial=[{'key': k, 'value': v} for k, v in self.get_object().computed_properties.items()],
        )
        return context


class QueryDelete(ResourceChildViewMixin, DeleteView):
    model = models.Query


class TestIndexingTemplate(ResourceChildViewMixin, DetailView):
    model = models.Query

    def get(self, request, *args, **kwargs):
        template = request.GET.get('template')
        if not template:
            return JsonResponse({'data': []})

        try:
            template = Template(template)
        except TemplateSyntaxError:
            return JsonResponse({'data': []})

        results = []
        features = self.get_object().features.values_list('data', flat=True)[:3]
        for feature in features:
            context = Context(feature.get('properties', {}))
            results.append(simplify(template.render(context)))

        return JsonResponse({'data': results})
