import os
import json
from decimal import Decimal

import mock
import pytest

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

from passerelle.base.models import ApiUser, AccessRight
from passerelle.contrib.solis_apa.models import SolisAPA
from passerelle.contrib.solis_apa import integration


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


def json_get_data(filename):
    with open(os.path.join(TEST_BASE_DIR, filename)) as fd:
        return json.load(fd)


@pytest.fixture
def setup(db):
    from webtest import TestApp
    api = ApiUser.objects.create(username='all',
                                 keytype='', key='')
    solis = SolisAPA.objects.create(base_url='https://whateever.com/rec/',
                                    slug='test')
    obj_type = ContentType.objects.get_for_model(solis)
    AccessRight.objects.create(codename='can_access', apiuser=api,
                               resource_type=obj_type, resource_pk=solis.pk)
    return TestApp(get_wsgi_application())


@pytest.fixture
def url():
    def get_url(name):
        return reverse('solis-apa-%s' % name, kwargs={'slug': 'test'})
    return get_url


@pytest.fixture(params=[
    json_get_data('premiere_demande_apa_domicile.json'),
    json_get_data('premiere_demande_apa_etablissement.json')])
def homonymie(request):
    return request.param


@mock.patch('passerelle.utils.LoggedRequest.post')
def test_instegration_demande_apa_domicile(mocked_post, setup, url):
    app = setup
    fake_response = '{"ImportIdResults":{"Items":[{"key":"indexDossier","value":359043},{"key":"indexBeneficiaire","value":458238},{"key":"indexDemande","value":221155}]}}'

    mocked_post.return_value = mock.Mock(status_code=200, content=fake_response,
                                         json=lambda: json.loads(fake_response))

    resp = app.post_json(url('integration'),
                         json_get_data('premiere_demande_apa_domicile.json'), status=200)

    resp.json['data']['indexDossier'] == 359043
    resp.json['data']['indexBeneficiaire'] == 458238
    resp.json['data']['indexDemande'] == 221155


@mock.patch('passerelle.utils.LoggedRequest.post')
def test_integration_demande_apa_etablissement(mocked_post, setup, url):
    app = setup
    fake_response = '{"ImportIdResults":{"Items":[{"key":"indexDossier","value":359043},{"key":"indexBeneficiaire","value":458238},{"key":"indexDemande","value":221155}]}}'

    mocked_post.return_value = mock.Mock(status_code=200, content=fake_response,
                                         json=lambda: json.loads(fake_response))

    resp = app.post_json(url('integration'),
                         json_get_data('premiere_demande_apa_etablissement.json'), status=200)

    resp.json['data']['indexDossier'] == 359043
    resp.json['data']['indexBeneficiaire'] == 458238
    resp.json['data']['indexDemande'] == 221155


def test_get_conjoint(setup, url, homonymie):
    data = integration.build_message(homonymie)
    if homonymie['display_id'] == '25-3':
        assert data['Conjoint']['bParticipeRevenus'] == False
        assert data['Conjoint']['dateNaissance'] == '1930-06-11'
        assert data['Conjoint']['nom'] == 'MCBEAL'
        assert data['Conjoint']['prenom'] == 'ALLY'
        assert data['Conjoint']['sexe'] == 'F'
        assert data['Conjoint']['situationFamiliale'] == 2
        assert data['RevenusImposition']['anneeReference'] == 2015
        assert Decimal(data['RevenusImposition']['revenuReference']) == Decimal(30000.0)
    else:
        assert 'Conjoint' not in data
        assert data['RevenusImposition']['anneeReference'] == 2015
        assert Decimal(data['RevenusImposition']['revenuReference']) == Decimal(32000.0)
