# 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/>.

from django.db import models
from django.utils.translation import ugettext_lazy as _

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


class ParameterTypeError(Exception):
    http_status = 400
    log_error = False


class Arcgis(BaseResource):
    base_url = models.CharField(_('SIG Url'), max_length=256)

    category = _('Geographic information system')

    class Meta:
        verbose_name = _('Arcgis Webservice')

    @classmethod
    def get_icon_class(cls):
        return 'gis'

    @endpoint(serializer_type='json-api')
    def district(self, request, lon=None, lat=None):
        if lon and lat:
            try:
                lon, lat = float(lon), float(lat)
                geometry = '{}, {}'.format(lon, lat)
                geometryType = 'esriGeometryPoint'
            except(ValueError,):
                raise ParameterTypeError('<lon> and <lat> must be floats')
        else:
            geometry = ''
            geometryType = 'esriGeometryEnvelope'

        params = {
            'where': '1=1',
            'f': 'pjson',
            'geometry': geometry,
            'geometryType': geometryType,
            'inSR': '4326',
            'outFields': '*',
            'outSR': '4326',
            'returnCountOnly': 'false',
            'returnDistinctValues': 'false',
            'returnExtentOnly': 'false',
            'returnGeometry': 'false',
            'returnIdsOnly': 'false',
            'returnM': 'false',
            'returnZ': 'false',
            'spatialRel': 'esriSpatialRelIntersects',
            'units': 'esriSRUnit_Foot',
        }

        url = '%s/query' % self.base_url

        response = self.requests.get(url, params=params)
        data = response.json()
        features = data['features']

        data = [
            {'id': feature['attributes'].get('NUMERO'), 'text': feature['attributes'].get('NOM')} for feature in features]

        if len(data) == 1:
            return data[0]
        return data
