import json
from unittest import mock

import pytest
from httmock import HTTMock

import tests.utils
from passerelle.contrib.lille_urban_card.models import LilleUrbanCard
from passerelle.utils.jsonresponse import APIError


@pytest.fixture
def connector(db):
    return tests.utils.setup_access_rights(
        LilleUrbanCard.objects.create(
            slug='test', base_url='http://localhost', username='test', password='secret'
        )
    )


TOKEN_ERROR_RESPONSE = '{"erreur":"Authentification échouée"}'
TOKEN_RESPONSE = '{"token": "eyJhbGciO..."}'


def mocked_http(url, request):
    if url.path == '/clu/ws/auth/connexion':
        return {'content': TOKEN_RESPONSE, 'status_code': 200}
    if url.path == '/clu/ws/demanderCarte':
        request_json = json.loads(request.body)
        if request_json.get('simulate_error') == 'doublon':
            error = {'erreur': 'Demande 113-9166 : 1 demande(s) ...'}
            return {'content': json.dumps(error), 'status_code': 409}
        elif request_json.get('simulate_error') == 'num_serie':
            error = {'statut': 'ERREUR_NUM_SERIE', 'erreur': '... pas valide'}
            return {'content': json.dumps(error), 'status_code': 404}
        content = {
            'n_demande_clu': 10000005,
            'request': request_json,  # for tests
        }
        return {'content': json.dumps(content), 'status_code': 200}
    if url.path.startswith('/clu/ws/consulterDemande/'):
        content = {
            "n_demande_clu": '...',
            "statut": "200",
            "statut_desc": "CARTE_PRODUITE_EXPEDIEE",
            "date": "2019-01-01 00:00:00",
        }
        return {'content': json.dumps(content), 'status_code': 200}
    if url.path == '/clu/ws/ajouterAbonnements':
        request_json = json.loads(request.body)
        if request_json.get('simulate_error') == 'data':
            error = {'statut': 'ERREUR_DONNEES', 'erreur': 'Demande vide...'}
            return {'content': json.dumps(error), 'status_code': 400}
        content = {
            'n_demande_clu': 10000005,
            'request': request_json,  # for tests
        }
        return {'content': json.dumps(content), 'status_code': 200}
    if url.path == '/clu/ws/modifierCodeSecret':
        request_json = json.loads(request.body)
        if request_json.get('simulate_error') == 'wrong num serie':
            error = {'statut': 'ERREUR_NUM_SERIE', 'erreur': 'Le numero de serie...'}
            return {'content': json.dumps(error), 'status_code': 404}
        return {'content': json.dumps({}), 'status_code': 200}
    if url.path == '/clu/ws/verifierMdp':
        assert 'numero_serie=XXX' in request.body and 'code_secret=1234' in request.body
        if 'simulate_error=wrong+num+serie' in request.body:
            error = {'statut': 'ERREUR_NUM_SERIE', 'erreur': 'Le numero de serie...'}
            return {'content': json.dumps(error), 'status_code': 404}
        return {'content': json.dumps({'message': 'Le mot de passe est valide'}), 'status_code': 200}
    if url.path in ('/clu/ws/revoquerCarte', '/clu/ws/revoquerAbonnement'):
        request_json = json.loads(request.body)
        if request_json.get('simulate_error') == 'doublon':
            error = {'erreur': 'La demande xx existe...'}
            return {'content': json.dumps(error), 'status_code': 409}
        return {'content': json.dumps({'message': 'ok'}), 'status_code': 200}
    if url.path == '/clu/ws/renouvelerAbonnements':
        request_json = json.loads(request.body)
        if request_json.get('simulate_error') == 'wrong num serie':
            error = {'statut': 'ERREUR_NUM_SERIE', 'erreur': 'Le numero de serie...'}
            return {'content': json.dumps(error), 'status_code': 409}
        return {'content': json.dumps({'n_demande_clu': 10000507}), 'status_code': 200}
    if url.path == '/clu/ws/consulterCarte':
        if url.query == 'numero_serie=ERROR':
            error = {'erreur': 'Pas de carte attribuee correspondante'}
            return {'content': json.dumps(error), 'status_code': 404}
        assert url.query == 'numero_serie=XXX'
        return {
            'content': json.dumps({'numero_serie': 'XXX', 'date_debut_abonnement': 'xx/xx/xxxx'}),
            'status_code': 200,
        }


@mock.patch('passerelle.utils.Request.post')
def test_get_token(mocked_post, app, connector):
    with pytest.raises(APIError):
        mocked_post.return_value = tests.utils.FakedResponse(content=TOKEN_ERROR_RESPONSE, status_code=400)
        connector.get_token()
    mocked_post.return_value = tests.utils.FakedResponse(content=TOKEN_RESPONSE, status_code=200)
    connector.get_token()


def test_csp(app, connector):
    endpoint = tests.utils.generic_endpoint_url('lille-urban-card', 'csp', slug=connector.slug)
    resp = app.get(endpoint)
    assert resp.json.get('data')


def test_card_request(app, connector):
    endpoint = tests.utils.generic_endpoint_url('lille-urban-card', 'card_request', slug=connector.slug)
    with HTTMock(mocked_http):
        resp = app.post_json(
            endpoint,
            params={
                'civilite': 'Monsieur',
                'code_postal': '59000',
                'ville': 'Lille',
                'photo': {'content': 'xxx'},
                'telephone': '01.02.03.04.05',
                'recevoir_journal_senior': 'Non',
                'service_zoo': 'Oui',
                'service_zoo_newsletter': 'Non',
            },
        )
        request = resp.json['data']['request']
        assert request['civilite'] == 1
        assert request['code_postal'] == 59000
        assert request['ville'] == 'LILLE'
        assert request['photo'] == 'xxx'
        assert request['telephone'] == '0102030405'
        assert request['services'] == [{'service': 'zoo', 'newsletter': 0}]
        assert resp.json['data']['n_demande_clu'] == 10000005

        # error handling
        resp = app.post_json(
            endpoint,
            params={
                'simulate_error': 'doublon',
                'civilite': 'Monsieur',
                'code_postal': '59000',
                'ville': 'Lille',
                'photo': {'content': 'xxx'},
                'telephone': '01.02.03.04.05',
                'recevoir_journal_senior': 'Non',
                'service_zoo': 'Oui',
                'service_zoo_newsletter': 'Non',
            },
            status=200,
        )
        assert resp.json['data']['status_code'] == 409

        resp = app.post_json(
            endpoint,
            params={
                'simulate_error': 'num_serie',
                'civilite': 'Monsieur',
                'code_postal': '59000',
                'ville': 'Lille',
                'photo': {'content': 'xxx'},
                'telephone': '01.02.03.04.05',
                'recevoir_journal_senior': 'Non',
                'service_zoo': 'Oui',
                'service_zoo_newsletter': 'Non',
            },
            status=200,
        )
        assert resp.json['data']['status_code'] == 404
        assert resp.json['data']['statut'] == 'ERREUR_NUM_SERIE'


def test_card_status(app, connector):
    endpoint = tests.utils.generic_endpoint_url('lille-urban-card', 'card_status', slug=connector.slug)
    with HTTMock(mocked_http):
        resp = app.get(endpoint + '?n_demande_clu=1234')
        assert resp.json['data']['statut_desc'] == 'CARTE_PRODUITE_EXPEDIEE'


def test_add_subscriptions(app, connector):
    endpoint = tests.utils.generic_endpoint_url('lille-urban-card', 'add_subscriptions', slug=connector.slug)
    with HTTMock(mocked_http):
        resp = app.post_json(
            endpoint,
            params={
                'n_demande_gru': 'XXX',
                'numero_serie': 'XXX',
                'civilite': 'Monsieur',
                'code_postal': '59000',
                'ville': 'Lille',
                'photo': {'content': 'xxx'},
                'telephone': '01.02.03.04.05',
                'recevoir_journal_senior': 'Non',
                'service_zoo': 'Oui',
                'service_zoo_newsletter': 'Non',
            },
        )
        request = resp.json['data']['request']
        assert request['civilite'] == 1
        assert request['code_postal'] == 59000
        assert request['ville'] == 'LILLE'
        assert request['photo'] == 'xxx'
        assert request['telephone'] == '0102030405'
        assert request['services'] == [{'service': 'zoo', 'newsletter': 0}]
        assert resp.json['data']['n_demande_clu'] == 10000005

        # error handling
        resp = app.post_json(
            endpoint,
            params={
                'simulate_error': 'data',
                'n_demande_gru': 'XXX',
                'numero_serie': 'XXX',
                'civilite': 'Monsieur',
                'code_postal': '59000',
                'ville': 'Lille',
                'photo': {'content': 'xxx'},
                'telephone': '01.02.03.04.05',
                'recevoir_journal_senior': 'Non',
                'service_zoo': 'Oui',
                'service_zoo_newsletter': 'Non',
            },
            status=200,
        )
        assert resp.json['data']['status_code'] == 400


def test_code_change(app, connector):
    endpoint = tests.utils.generic_endpoint_url('lille-urban-card', 'code_change', slug=connector.slug)
    with HTTMock(mocked_http):
        resp = app.post_json(
            endpoint,
            params={
                'numero_serie': 'XXX',
                'ancien': '1234',
                'nouveau': '2345',
                'confirmation_nouveau': '2345',
            },
        )
        assert resp.json['err'] == 0

        # error handling
        resp = app.post_json(
            endpoint,
            params={
                'simulate_error': 'wrong num serie',
                'numero_serie': 'XXX',
                'ancien': '1234',
                'nouveau': '2345',
                'confirmation_nouveau': '2345',
            },
            status=200,
        )
        assert resp.json['err'] == 1
        assert resp.json['data']['status_code'] == 404


def test_code_check(app, connector):
    endpoint = tests.utils.generic_endpoint_url('lille-urban-card', 'code_check', slug=connector.slug)
    with HTTMock(mocked_http):
        resp = app.post_json(
            endpoint,
            params={
                'numero_serie': 'XXX',
                'password': '1234',
            },
        )
        assert resp.json['err'] == 0

        # error handling
        resp = app.post_json(
            endpoint,
            params={
                'simulate_error': 'wrong num serie',
                'numero_serie': 'XXX',
                'password': '1234',
            },
            status=200,
        )
        assert resp.json['err'] == 1


def test_card_info(app, connector):
    endpoint = tests.utils.generic_endpoint_url('lille-urban-card', 'card_info', slug=connector.slug)
    with HTTMock(mocked_http):
        resp = app.get(
            endpoint,
            params={
                'numero_serie': 'XXX',
            },
        )
        assert resp.json['err'] == 0

        # error handling
        resp = app.get(
            endpoint,
            params={
                'numero_serie': 'ERROR',
            },
            status=200,
        )
        assert resp.json['err'] == 1

    # empty numero_serie, do not even pass request
    resp = app.get(
        endpoint,
        params={
            'numero_serie': '',
        },
    )
    assert resp.json['err'] == 1


def test_card_revocation(app, connector):
    endpoint = tests.utils.generic_endpoint_url('lille-urban-card', 'card_revocation', slug=connector.slug)
    with HTTMock(mocked_http):
        resp = app.post_json(
            endpoint,
            params={
                'n_demande_gru': '12-123',
                'numero_serie': 'XXX',
                'date_demande': '05/02/2020',
            },
        )
        assert resp.json['err'] == 0

        # error handling
        resp = app.post_json(
            endpoint,
            params={
                'simulate_error': 'doublon',
                'n_demande_gru': '12-123',
                'numero_serie': 'XXX',
                'date_demande': '05/02/2020',
            },
            status=200,
        )
        assert resp.json['err'] == 1
        assert resp.json['data']['status_code'] == 409


def test_subscription_revocation(app, connector):
    endpoint = tests.utils.generic_endpoint_url(
        'lille-urban-card', 'subscription_revocation', slug=connector.slug
    )
    with HTTMock(mocked_http):
        resp = app.post_json(
            endpoint,
            params={
                'n_demande_gru': '12-123',
                'numero_serie': 'XXX',
                'date_demande': '05/02/2020',
                'service_zoo': 'Oui',
                'service_zoo_newsletter': 'Non',
            },
        )
        assert resp.json['err'] == 0

        # error handling
        resp = app.post_json(
            endpoint,
            params={
                'simulate_error': 'doublon',
                'n_demande_gru': '12-123',
                'numero_serie': 'XXX',
                'date_demande': '05/02/2020',
                'service_zoo': 'Oui',
                'service_zoo_newsletter': 'Non',
            },
            status=200,
        )
        assert resp.json['err'] == 1
        assert resp.json['data']['status_code'] == 409


def test_subscription_renewal(app, connector):
    endpoint = tests.utils.generic_endpoint_url(
        'lille-urban-card', 'subscription_renewal', slug=connector.slug
    )
    with HTTMock(mocked_http):
        resp = app.post_json(
            endpoint,
            params={
                'n_demande_gru': '12-123',
                'numero_serie': 'XXX',
                'date_demande': '05/02/2020',
            },
        )
        assert resp.json['err'] == 0

        # error handling
        resp = app.post_json(
            endpoint,
            params={
                'simulate_error': 'wrong num serie',
                'n_demande_gru': '12-123',
                'numero_serie': 'XXX',
                'date_demande': '05/02/2020',
            },
            status=200,
        )
        assert resp.json['err'] == 1
        assert resp.json['data']['status_code'] == 409
