# -*- coding: utf-8 -*-
import pytest
import mock
import utils
import json

from django.core.management import call_command

from base_adresse.models import BaseAdresse, StreetModel

from passerelle.views import WrongParameter


FAKED_CONTENT = '{"limit": 1, "attribution": "BAN", "version": "draft", "licence": "ODbL 1.0", "query": "plop", "type": "FeatureCollection", "features": [{"geometry": {"type": "Point", "coordinates": [-0.593775, 47.474633]}, "properties": {"citycode": "49007", "name": "Rue Roger Halope", "id": "49007_6950_be54bd", "city": "Angers", "context": "49, Maine-et-Loire, Pays de la Loire", "score": 0.14097272727272728, "label": "Rue Roger Halope 49000 Angers", "postcode": "49000", "type": "street"}, "type": "Feature"}]}'

FAKE_DATA = ''
@pytest.fixture
def base_adresse(db):
    return utils.setup_access_rights(BaseAdresse.objects.create(slug='base-adresse', zipcode='73'))

@pytest.fixture
def street(db):
    return StreetModel.objects.create(city=u'Chambéry',
                                      name=u'Une rüê très äccentuéè',
                                      zipcode=u'73000',
                                      type=u'street',
                                      citycode=u'73001')

@mock.patch('passerelle.utils.LoggedRequest.get')
def test_base_adresse_search(mocked_get, app, base_adresse):
    endpoint = utils.generic_endpoint_url('base-adresse', 'search', slug=base_adresse.slug)
    assert endpoint == '/base-adresse/base-adresse/search'
    mocked_get.return_value = utils.FakedResponse(content=FAKED_CONTENT, status_code=200)
    resp = app.get(endpoint, {'q': 'plop'}, status=200)
    data = resp.json[0]
    assert data['lat'] == '47.474633'
    assert data['lon'] == '-0.593775'
    assert data['display_name'] == 'Rue Roger Halope 49000 Angers'


def test_base_adresse_search_qs(app, base_adresse, mock_api_adresse_data_gouv_fr_search):
    resp = app.get('/base-adresse/%s/search?q=plop' % base_adresse.slug)
    assert 'display_name' in resp.json[0]


def test_base_adresse_search_qs_zipcode(app, base_adresse, mock_api_adresse_data_gouv_fr_search):
    resp = app.get('/base-adresse/%s/search?q=plop&zipcode=49000' % base_adresse.slug)
    assert 'display_name' in resp.json[0]


def test_base_adresse_search_qs_parameters_error(app, base_adresse,
                                                 mock_api_adresse_data_gouv_fr_search):
    # plain serializer
    with pytest.raises(WrongParameter):
        app.get('/base-adresse/%s/search' % base_adresse.slug, status=400)
    # json-api serializer
    resp = app.get('/base-adresse/%s/streets?zipcode=13400&coin=zz' % base_adresse.slug, status=400)
    assert resp.json['err'] == 1
    assert 'coin' in resp.json['err_desc']
    # signature and format are ignored
    app.get('/base-adresse/%s/streets?zipcode=13400&signature=zz&format=jsonp'
            '&raise=1&jsonpCallback=f' % base_adresse.slug)


def test_base_adresse_reverse(app, base_adresse, mock_api_adresse_data_gouv_fr_reverse):
    resp = app.get('/base-adresse/%s/reverse?lon=-0.593775&lat=47.474633' % base_adresse.slug)

    assert 'display_name' in resp.json

@mock.patch('base_adresse.management.commands.update_streets.urllib.urlretrieve')
def test_base_adresse_command_update(mock_url, db, base_adresse):
    mock_url.return_value = ('tests/data/update_streets_test.bz2',)
    call_command('update_streets')
    streets = StreetModel.objects.all()
    assert len(streets) == 3
    street = StreetModel.objects.get(id=1)
    assert street.name == 'Chemin de la Vie, LA GRANGE DU TRIEU'
    assert street.zipcode == '73610'
    assert street.type == 'street'
    assert street.city == 'Aiguebelette-le-Lac'
    assert street.citycode == '73001'

def test_base_adresse_streets_unaccent(app, base_adresse, street):
    resp = app.get('/base-adresse/%s/streets?q=une rue tres acc' % base_adresse.slug)
    data = json.loads(resp.body)
    assert 'data' in data
    result = data['data'][0]
    assert result['city'] == street.city
    assert result['text'] == street.name
    assert result['citycode'] == street.citycode
    assert result['zipcode'] == street.zipcode
    assert result['id'] == street.id
