# 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 xml.etree import ElementTree as ET

from django import forms
from django.forms import formset_factory
from django.utils.translation import gettext_lazy as _

from passerelle.base.forms import BaseQueryFormMixin

from . import models


class ComputedPropertyForm(forms.Form):
    key = forms.CharField(label=_('Property name'), required=False)
    value = forms.CharField(
        label=_('Value template'), widget=forms.TextInput(attrs={'size': 60}), required=False
    )


ComputedPropertyFormSet = formset_factory(ComputedPropertyForm)


class QueryForm(BaseQueryFormMixin, forms.ModelForm):
    class Meta:
        model = models.Query
        fields = '__all__'
        exclude = ['resource', 'computed_properties']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields[
                'indexing_template'
            ].widget.template_name = 'opengis/widgets/indexing_template_widget.html'

    def clean_filter_expression(self):
        filter_expression = self.cleaned_data['filter_expression']
        if filter_expression:
            try:
                ET.fromstring(filter_expression)
            except ET.ParseError:
                raise forms.ValidationError(_('Filter is not valid XML.'))
        return filter_expression
