import json
from unittest import mock

import pytest

import tests.utils
from passerelle.contrib.adict.models import Adict

FAKE_FEATURE_INFO = json.dumps(
    {
        'type': 'FeatureCollection',
        'features': [
            {
                'type': 'Feature',
                'properties': {
                    'id': 51,
                    'type': 'secteur_maternelle',
                    'url': None,
                    'description': None,
                    'nom': 'NEUFELD',
                },
                'geometry': {},
            }
        ],
    }
)


@pytest.fixture
def connector(db):
    return tests.utils.setup_access_rights(
        Adict.objects.create(
            slug='test',
            service_root_url='http://adict.example.net/',
            api_token='xyz',
            sector_type='secteur_maternelle',
        )
    )


@mock.patch('passerelle.utils.Request.get')
def test_feature_info(mocked_get, app, connector):
    endpoint = tests.utils.generic_endpoint_url('adict', 'feature_info', slug=connector.slug)
    assert endpoint == '/adict/test/feature_info'
    mocked_get.return_value = tests.utils.FakedResponse(content=FAKE_FEATURE_INFO, status_code=200)
    resp = app.get(endpoint, params={'lat': '48.570472877', 'lon': '7.75659804'})
    assert mocked_get.call_args[0][0] == 'http://adict.example.net/api/v1.0/secteurs'
    assert mocked_get.call_args[1]['params']['x'] == '7.75659804'
    assert mocked_get.call_args[1]['params']['y'] == '48.570472877'
    assert resp.json['data']['nom'] == 'NEUFELD'


@mock.patch('passerelle.utils.Request.get')
def test_no_feature_info(mocked_get, app, connector):
    endpoint = tests.utils.generic_endpoint_url('adict', 'feature_info', slug=connector.slug)
    assert endpoint == '/adict/test/feature_info'
    mocked_get.return_value = tests.utils.FakedResponse(content=json.dumps({'features': []}), status_code=200)
    resp = app.get(endpoint, params={'lat': '48.570472877', 'lon': '7.75659804'})
    assert resp.json['err'] == 1
    assert resp.json['err_msg'] == 'not found'
