# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2017 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.db import models
from django.utils.translation import gettext_lazy as _

from passerelle.base.models import BaseResource
from passerelle.utils.api import endpoint


class Adict(BaseResource):
    category = _('Geographic information system')
    service_root_url = models.URLField(_('Service Root URL'), max_length=256)
    sector_type = models.CharField(_('Sector Type'), max_length=256)
    api_token = models.CharField(_('API Token'), max_length=256)

    class Meta:
        verbose_name = _('ADICT (Strasbourg GIS)')

    @endpoint(
        perm='can_access',
        description=_('Get feature info'),
        parameters={
            'lat': {'description': _('Latitude'), 'example_value': '48.5704728777251'},
            'lon': {'description': _('Longitude'), 'example_value': '7.75659804140393'},
        },
    )
    def feature_info(self, request, lat, lon):
        query_args = {'x': lon, 'y': lat, 'srid': '4326'}
        query_args['token'] = self.api_token
        query_args['sector_type'] = self.sector_type
        response = self.requests.get(
            self.service_root_url.strip('/') + '/api/v1.0/secteurs',
            params={
                'x': lon,
                'y': lat,
                'srid': '4326',
                'token': self.api_token,
                'sector_type': self.sector_type,
            },
        )
        response.raise_for_status()
        data = response.json()
        if len(data.get('features') or []) == 0:
            return {'err': 1, 'err_msg': 'not found'}
        return {'err': 0, 'data': data['features'][0]['properties']}
