import mock
import pytest
import urlparse
from StringIO import StringIO

from passerelle.base.models import ApiUser, AccessRight
from clicrdv.models import ClicRdv


@pytest.fixture
def connector(db):
    return ClicRdv.objects.create(slug='test', group_id='5242', apikey='test', username='test',
                        password='test')


@mock.patch('urllib2.urlopen')
def test_urlopen_call(urlopen, app, connector):
    urlopen.return_value = StringIO('"foo"')
    rjson = connector.get_json('bar')
    assert urlopen.call_count == 1
    req = urlopen.call_args[0][0]
    assert req.get_full_url().startswith('https://sandbox.clicrdv.com/api/v1/groups/5242/bar')


@mock.patch('clicrdv.models.ClicRdv.get_json')
def test_interventionsets(mocked_get, app, connector):
    mocked_get.return_value = {
            "totalRecords": 2,
            "records": [
                {
                    "sort": 1,
                    "publicname": "Une Demande de Passeport",
                    "name": "Demande",
                    "id": 7032,
                    "group_id": 5242,
                },
                {
                    "sort": 2,
                    "publicname": "Un Retrait de Passeport",
                    "name": "Retrait",
                    "id": 7033,
                    "group_id": 5242,
                },
            ]}
    resp = app.get('/clicrdv/test/interventionsets/')
    assert len(resp.json.get('data')) == 2
    assert resp.json.get('data')[0]['text'] == 'Une Demande de Passeport'


@mock.patch('clicrdv.models.ClicRdv.get_json')
def test_interventionsets_details(mocked_get, app, connector):
    mocked_get.return_value = {
            "totalRecords": 2,
            "records": [
                {
                    "sort": 1,
                    "publicname": "pour une personne",
                    "description": None,
                    "name": "1 personne",
                    "interventionset_id": 7032,
                    "group_id": 5242,
                    "id": 63258,
                    "abbr": "1 demande"
                    },
                {
                    "sort": 2,
                    "publicname": "pour deuxs personnes",
                    "description": None,
                    "name": "2 personnes",
                    "interventionset_id": 7032,
                    "group_id": 5242,
                    "id": 63259,
                    "abbr": "2 demandes"
                },
            ]}

    resp = app.get('/clicrdv/test/interventionsets/7032/')
    assert len(resp.json.get('data')) == 2
    assert resp.json.get('data')[0]['text'] == 'pour une personne'

@mock.patch('urllib2.urlopen')
def test_interventions_get_datetimes(urlopen, app, connector):
    urlopen.return_value = StringIO('{"availabletimeslots": []}')
    resp = app.get('/clicrdv/test/interventions/63258/dates/')
    assert resp.json.get('data') == []
    assert resp.json.get('err') == 0
    assert urlopen.call_count == 1
    url = urlopen.call_args[0][0].get_full_url()
    # https://sandbox.clicrdv.com/api/v1/groups/5242/availabletimeslots?
    #   intervention_ids[]=63258&start=2016-09-21&end=2017-09-22&apikey=test&format=json
    scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
    query = urlparse.parse_qs(query, keep_blank_values=True)
    assert scheme == 'https'
    assert netloc == 'sandbox.clicrdv.com'
    assert path == '/api/v1/groups/5242/availabletimeslots'
    assert params == ''
    assert fragment == ''
    assert query['intervention_ids[]'] == ['63258']
    assert 'start' in query
    assert 'end' in query
    assert query['apikey'] == ['test']
    assert query['format'] == ['json']

    urlopen.return_value = StringIO('''{"availabletimeslots": [
            { "start": "2016-09-21 12:34:56" },
            { "start": "2016-09-22 11:22:33" }
        ]}''')
    resp = app.get('/clicrdv/test/interventions/63258/dates/').json
    assert urlopen.call_count == 2
    assert resp.get('err') == 0
    assert len(resp.get('data')) == 2
    assert resp['data'][0] == {'id': '2016-09-21', 'text': '21 September 2016'}
    assert resp['data'][1] == {'id': '2016-09-22', 'text': '22 September 2016'}

    urlopen.return_value = StringIO('''{"availabletimeslots": [
            { "start": "2016-09-22 11:22:33" },
            { "start": "2016-09-21 12:34:56" }
        ]}''') # will be sorted
    resp = app.get('/clicrdv/test/interventions/63258/datetimes/').json
    assert urlopen.call_count == 3
    assert resp.get('err') == 0
    assert len(resp.get('data')) == 2
    assert resp['data'][0] == {'id': '2016-09-21-12:34:56', 'text': '21 September 2016 12:34'}
    assert resp['data'][1] == {'id': '2016-09-22-11:22:33', 'text': '22 September 2016 11:22'}

    urlopen.return_value = StringIO('''{"availabletimeslots": [
            { "start": "2016-09-21 12:34:56" },
            { "start": "2016-09-21 11:22:33" }
        ]}''') # will be sorted
    resp = app.get('/clicrdv/test/interventions/63258/2016-09-21/times').json
    assert urlopen.call_count == 4
    url = urlopen.call_args[0][0].get_full_url()
    scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
    query = urlparse.parse_qs(query, keep_blank_values=True)
    assert query['start'] == ['2016-09-21 00:00:00']
    assert query['end'] == ['2016-09-21 23:59:59']
    assert resp.get('err') == 0
    assert len(resp.get('data')) == 2
    assert resp['data'][0] == {'id': '11:22:33', 'text': '11:22'}
    assert resp['data'][1] == {'id': '12:34:56', 'text': '12:34'}
