import os
import json

import pytest
import mock


from django.core.urlresolvers import reverse
from django.contrib.contenttypes.models import ContentType

from passerelle.base.models import ApiUser, AccessRight
from passerelle.contrib.arcgis.models import Arcgis


TEST_BASE_DIR = os.path.join(os.path.dirname(__file__), 'data', 'nancy_arcgis')


def get_file_content(filename):
    with open(os.path.join(TEST_BASE_DIR, filename), 'rb') as fd:
        return fd.read()


class MockedRequestsResponse(mock.Mock):

    def json(self):
        return json.loads(self.content)


@pytest.fixture
def setup(db):
    api = ApiUser.objects.create(username='all',
                                 keytype='', key='')
    arcgis = Arcgis.objects.create(base_url='https://whatevever.org/layer/0', slug='test')
    obj_type = ContentType.objects.get_for_model(arcgis)
    AccessRight.objects.create(codename='can_access', apiuser=api,
                               resource_type=obj_type, resource_pk=arcgis.pk)
    return arcgis


@pytest.fixture
def url():
    return reverse('generic-endpoint', kwargs={
        'connector': 'arcgis', 'slug': 'test', 'endpoint': 'district'})


def test_get_district_parameters_error(app, setup, url):
    resp = app.get(url, {'lon': 'lon', 'lat': 'lat'}, status=400)
    assert resp.json['err_desc'] == '<lon> and <lat> must be floats'


@mock.patch('passerelle.utils.LoggedRequest.get')
def test_get_district(mocked_get, app, setup, url):
    mocked_get.return_value = MockedRequestsResponse(
        content=get_file_content('sigresponse.json'),
        status_code=200)

    resp = app.get(url, {'lon': 6.172122, 'lat': 48.673836}, status=200)
    data = resp.json['data']
    assert data['id'] == 4
    assert data['text'] == 'HAUSSONVILLE / BLANDAN / MON DESERT / SAURUPT'


@mock.patch('passerelle.utils.LoggedRequest.get')
def test_get_all_district(mocked_get, app, setup, url):
    mocked_get.return_value = MockedRequestsResponse(
        content=get_file_content('all_districts.json'),
        status_code=200)

    resp = app.get(url, status=200)
    data = resp.json['data']
    assert len(data) == 7
