import freezegun
import pytest
from httmock import HTTMock, response

import tests.utils
from passerelle.apps.airquality.models import AirQuality

SAMPLE_RESPONSE = {
    "licence": "https://opendatacommons.org/licenses/odbl/",
    "commune": "LYON-1ER-ARRONDISSEMENT",
    "code_insee": "69381",
    "indices": {
        "current_page": 1,
        "data": [
            {
                "date": "2020-12-22",
                "valeur": "26.6503231768126",
                "couleur_html": "#5CCB60",
                "qualificatif": "Bon",
                "type_valeur": "prévision",
            },
            {
                "date": "2020-12-21",
                "valeur": "21.6876695818178",
                "couleur_html": "#5CCB60",
                "qualificatif": "Bon",
                "type_valeur": "prévision",
            },
            {
                "date": "2020-12-20",
                "valeur": "26.1405508214683",
                "couleur_html": "#5CCB60",
                "qualificatif": "Bon",
                "type_valeur": "prévision",
            },
        ],
    },
    "first_page_url": "https://api.atmo-aura.fr/communes/69381/indices?api_token=XXX&page=1",
    "from": 1,
    "last_page": 23,
    "last_page_url": "https://api.atmo-aura.fr/communes/69381/indices?api_token=XXX&page=23",
    "next_page_url": "https://api.atmo-aura.fr/communes/69381/indices?api_token=XXX&page=2",
    "path": "https://api.atmo-aura.fr/communes/69381/indices",
    "per_page": 50,
    "prev_page_url": None,
    "to": 50,
    "total": 1137,
}

SAMPLE_COMMENT_RESPONSE = {
    "licence": "https://opendatacommons.org/licenses/odbl/",
    "commentaire": "Jeudi 11 mai, le temps perturbé a permis d’avoir une bonne qualité de l’air sur la zone de surveillance.",
}


@pytest.fixture
def airquality(db):
    return AirQuality.objects.create(slug='atmo', atmo_aura_api_token='XXX')


def mocked_http(url, request):
    if url.path.startswith('/commune'):
        return response(200, SAMPLE_RESPONSE, request=request)
    if url.path.startswith('/commentaire'):
        return response(200, SAMPLE_COMMENT_RESPONSE, request=request)


@freezegun.freeze_time('2020-12-21')
def test_airquality_details(app, airquality):
    endpoint = tests.utils.generic_endpoint_url('airquality', 'details', slug=airquality.slug)
    assert endpoint == '/airquality/atmo/details'
    with HTTMock(mocked_http):
        resp = app.get(endpoint + '/fr/lyon/', status=200)
        assert resp.json['data']['latest']['value'] == '21.6876695818178'
        assert 'Jeudi 11 mai, le temps' in resp.json['data']['comment']


def test_airquality_details_unknown_city(app, airquality):
    endpoint = tests.utils.generic_endpoint_url('airquality', 'details', slug=airquality.slug)
    app.get(endpoint + '/fr/paris/', status=404)
