# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2021  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 urllib.parse import urljoin

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

from passerelle.base.models import BaseResource, HTTPResource
from passerelle.utils.api import endpoint
from passerelle.utils.jsonresponse import APIError

CREATE_SCHEMA = {
    '$schema': 'http://json-schema.org/draft-04/schema#',
    "type": "object",
    'required': ['demandeur', 'id_typeinterv', 'id_urgence'],
    'properties': {
        'demandeur': {
            'description': "Nom du demandeur",
            'type': 'string',
        },
        'id_typeinterv': {
            'description': "Type de l'intervention",
            'type': 'string',
        },
        'id_urgence': {
            'description': 'Urgence',
            'type': 'string',
        },
        'id_qualification': {
            'description': 'Qualification',
            'type': 'string',
        },
        'observations': {
            'description': 'Observations',
            'type': 'string',
        },
        'elements': {
            'description': "Identifiant de l'objet : liste séparée par ':'",
            'type': 'string',
            'pattern': r'^[0-9A-Z :]+$',
        },
        'nom_rue': {
            'description': 'Adresse',
            'type': 'string',
        },
    },
}

QUERY_SCHEMA = {
    '$schema': 'http://json-schema.org/draft-04/schema#',
    "type": "object",
    'properties': {
        'id_intervention': {
            'description': 'Rechercher une intervention par son numéro'
            ' (non cumulable avec les autres filtres)',
            'type': 'string',
        },
        'date_debut_demande': {
            'description': 'Rechercher toutes les interventions dont la date de demande'
            ' est supérieure ou égale à la date renseignée (YYYY-MM-DD)',
            'type': 'string',
        },
        'date_fin_demande': {
            'description': 'Rechercher toutes les interventions dont la date de demande'
            ' est inférieure ou égale à la date renseignée (YYYY-MM-DD)',
            'type': 'string',
        },
        'insee': {
            'description': "Code INSEE de la commune : liste séparée par ':'",
            'type': 'string',
            'pattern': r'^[0-9A-Z :]+$',
        },
    },
}


class Sigerly(BaseResource, HTTPResource):
    base_url = models.CharField(
        max_length=256,
        blank=False,
        verbose_name=_('Webservice Base URL'),
        help_text='exemple: https://sig.sigerly.fr/syecl_intervention_preprod/webservicev2/',
    )

    category = _('Business Process Connectors')

    class Meta:
        verbose_name = 'Sigerly'

    def request(self, uri, json):
        url = urljoin(self.base_url, uri)
        headers = {'Accept': 'application/json'}

        response = self.requests.post(url, json=json, headers=headers)
        if not response.ok:
            raise APIError('Sigerly returned bad response code from API: %s' % response.status_code)
        try:
            json_response = response.json()
        except ValueError:
            raise APIError('Sigerly returned invalid JSON content: %r' % response.content[:1024])
        return json_response

    @endpoint(
        perm='can_access',
        methods=['post'],
        description='Envoyer une demande',
        post={'request_body': {'schema': {'application/json': CREATE_SCHEMA}}},
    )
    def create(self, request, post_data):
        post_data['id_typeinterv'] = int(post_data['id_typeinterv'])
        post_data['id_urgence'] = int(post_data['id_urgence'])
        post_data['id_qualification'] = int(post_data['id_qualification'])
        if 'elements' in post_data:
            post_data['elements'] = [x.strip() for x in post_data['elements'].split(':') if x.strip()]

        response = self.request('createIntervention.php', json=post_data)
        if not response.get('success', None):
            raise APIError(response.get('message', None))
        if not response.get('message', None):
            raise APIError('No intervention id returned')
        return {'data': response}

    @endpoint(
        perm='can_access',
        methods=['post'],
        description='Récupérer le statut d’une demande',
        post={'request_body': {'schema': {'application/json': QUERY_SCHEMA}}},
    )
    def query(self, request, post_data):
        if post_data.get('id_intervention', None):
            post_data['id_intervention'] = int(post_data['id_intervention'])
            post_data.pop('date_debut_demande', None)
            post_data.pop('date_fin_demande', None)
            post_data.pop('insee', None)
        else:
            post_data.pop('id_intervention', None)
            if post_data.get('insee'):
                post_data['insee'] = [x.strip() for x in post_data['insee'].split(':') if x.strip()]

        response = self.request('getIntervention.php', json=post_data)
        for record in response:
            record['id'] = record.get('code_inter')
            record['text'] = '%(code_inter)s: %(libelle_intervention)s' % record
        return {'data': response}
